Skip to content

Instantly share code, notes, and snippets.

@cfg
Created May 21, 2012 13:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cfg/2762257 to your computer and use it in GitHub Desktop.
Save cfg/2762257 to your computer and use it in GitHub Desktop.
Get the directory the current bash script is located in.
# From discussion at http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# Is a useful one-liner which will give you the full directory name of the script no matter where it is being
# called from
# Or, to get the dereferenced path (all directory symlinks resolved), do this:
DIR="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# These will work as long as the last component of the path used to find the
# script is not a symlink (directory links are OK). If you want to also resolve any links to the script itself,
# you need a multi-line solution:
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ] ; do SOURCE="$(readlink "$SOURCE")"; done
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
# This last one will work with any combination of aliases, source, bash -c, symlinks, etc.
@medington
Copy link

The last example doesn't work if the symlink is a relative path and the directory it's executed from is not the directory containing the script.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment