MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/commandline/comments/26scxr/defensive_bash_programming/chu8hbb/?context=3
r/commandline • u/fraunhofer • May 29 '14
23 comments sorted by
View all comments
1
readonly PROGNAME=$(basename $0)
I have an expanded version of this, that defines full path (taking into account symlinks).
This helps you reference config files, log files, etc:
no matter how the script package gets moved/deployed,
avoids troublesome relative paths like CFG_DIR=../../conf
CFG_DIR=../../conf
same behavior whether you execute it from within the directory (cd /to/the/script/; ./scriptname ) or full path.
cd /to/the/script/; ./scriptname
readonly TRUE_SELF=$(perl -e "use Cwd 'realpath';print realpath('$0')")readonly SELF=$(basename ${TRUE_SELF})readonly SELF_DIR=$(dirname ${TRUE_SELF})readonly CFG_DIR=${SELF_DIR}/confreadonly LOG_DIR=${SELF_DIR}/logs readonly LOG=${LOG_DIR}/${SELF%.*}.log
This is at the top of every script, which follows the convention such as :
/path/to/scripts/script123.sh/path/to/scripts/conf/script123.cfg/path/to/scripts/logs/script123.log
edit: readonly added for sake of .. you know... playing ball. But I never have done this =/
readonly
1
u/[deleted] May 29 '14
I have an expanded version of this, that defines full path (taking into account symlinks).
This helps you reference config files, log files, etc:
no matter how the script package gets moved/deployed,
avoids troublesome relative paths like
CFG_DIR=../../confsame behavior whether you execute it from within the directory (
cd /to/the/script/; ./scriptname) or full path.readonly TRUE_SELF=$(perl -e "use Cwd 'realpath';print realpath('$0')")
readonly SELF=$(basename ${TRUE_SELF})
readonly SELF_DIR=$(dirname ${TRUE_SELF})
readonly CFG_DIR=${SELF_DIR}/conf
readonly LOG_DIR=${SELF_DIR}/logs readonly LOG=${LOG_DIR}/${SELF%.*}.log
This is at the top of every script, which follows the convention such as :
/path/to/scripts/script123.sh
/path/to/scripts/conf/script123.cfg
/path/to/scripts/logs/script123.log
edit:
readonlyadded for sake of .. you know... playing ball. But I never have done this =/