1

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?

Alexander Mills
  • 9,330
  • 19
  • 95
  • 180

2 Answers2

2

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.

oliv
  • 2,586
  • 9
  • 14
0

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"
Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250