I have a bash script here:
$GOPATH/
src/
build.sh
and in build.sh I have:
export GOPATH="$(cd $(dirname "$BASH_SOURCE") && pwd)"
is there a shorter way to get the containing dir of build.sh?
To get the directory where the script is located, use this:
readlink -f $(dirname $0)
As said in the bash man page, $0 is set to the name of the file.
readlink -f gets the absolute path of that directory.
Extending the BASH_SOURCE idea, check to see if it contains an absolute path; if so, use it directly, otherwise prepend PWD. Afterwards, strip off the trailing slash and anything following it, leaving just the containing directory:
case ${BASH_SOURCE[0]} in
( /* )
p=${BASH_SOURCE[0]}
;;
( * )
p=${PWD}/${BASH_SOURCE[0]}
;;
esac
p=${p%/*}
printf "%s\n" "$p"