Skip to content

Instantly share code, notes, and snippets.

@insanity54
Last active October 22, 2015 23:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save insanity54/fcc93e45cd297e56e1bb to your computer and use it in GitHub Desktop.
Save insanity54/fcc93e45cd297e56e1bb to your computer and use it in GitHub Desktop.
Get the absolute path of the directory of the bash script
#!/bin/bash
# Gets the absolute path of the directory of this bash script. works in Linux & OSX
# greets to https://stackoverflow.com/questions/394230/detect-the-os-from-a-bash-script
# greets to https://stackoverflow.com/questions/3572030/bash-script-absolute-path-with-osx
function detectplatform {
platform='unknown'
unamestr=`uname`
if [[ "$unamestr" == 'Linux' ]]; then
platform='linux'
elif [[ "$unamestr" == 'Darwin' ]]; then
platform='darwin'
fi
}
function osxrealpath {
[[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"
}
function getbindir {
if [[ $platform == 'linux' ]]; then
echo "$(dirname "$(readlink -fm "$0")")" # linux
elif [[ $platform == 'darwin' ]]; then
echo "$(dirname "$(osxrealpath $0)")" # osx
fi
}
detectplatform
echo "absolute path of this script's directory is $(getbindir)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment