Created
May 21, 2012 13:14
-
-
Save cfg/2762257 to your computer and use it in GitHub Desktop.
Get the directory the current bash script is located in.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.