1

I have a SunOS system, which is what complicates this situation from being simple.

I have some scripts that run from different paths (unavoidable) and the system has a path structure that has the "System Environment" in the path, which I can then extract from the path. I have a simple script which is called before or sourced from every other script to get the Environment and set several other common variables. The problem is, now that there are 3 different areas that may be calling this script, it doesn't properly extract the Environment from the path.

Here are simple examples of the 3 paths that might exist:

  • /dir1/dir2/${ENV}/bin/script1.ksh
  • /dir1/dir2/${ENV}/services/service_name/script2.ksh
  • /dir1/dir2/${ENV}/services/service_name/log/script3.ksh

I'd like to have 1 script, that would be able to get ${ENV}, not matter which one of the paths was provided as opposed to my current strategy of 3 separate ones.

Here is how I currently get the first ${ENV}:

#!/bin/ksh

export BASE_DIR=${0%/*/*}
export ENV=${BASE_DIR##*/}

2nd Script:

#!/bin/ksh

export CURR_DIR=$( cd -- "$(dirname -- "$(command -v -- "$0")")" && pwd)
export BASE_DIR=${CURR_DIR%/*/*}
export ENV=${BASE_DIR##*/}

As I stated, this is a SunOS system, so it has an old limited version of KSH. No set -A or substitution.

Any ideas on the best strategy to limit my repetitiveness of scripts?

Thanks.

Dermot Canniffe
  • 167
  • 1
  • 8
Audi.RS4
  • 25
  • 6

1 Answers1

0

It looks from your example that your ${ENV} directory is a fixed depth from root, in which case you can easily get the name of the directory by starting from the other end;

export ENV=`pwd | sed -e "s%\(/dir1/dir2/\)\([^/]*\).*%\2%"`

I'm using '%' so I can match '/' without escaping. Without knowing specifics about what version of SunOS/Solaris you're using I can't be certain how compliant your sed is but Bruce Barnett includes it in his tutorials which are very closely aligned with late SunOS and early Solaris versions.

If your scripts are all called by the same user, then you might want to include the above in that user's .profile, then the ENV variable will be accessible to all scripts owned/executed by that user.

UPDATE: Lee E. McMahon's "SED -- A Non-Interactive Text Editor" - written in 1978 - includes pattern grouping using escaped parentheses, so it should work for you on SunOS. :)

Dermot Canniffe
  • 167
  • 1
  • 8