Is there a command to go inside a bash .sh
script that will provide the full path to the directory containing that script?
2 Answers
See the answers on Get the source directory of a Bash script from within the script itself. The accepted one recommends
#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
but reading all the answers gives a lot of alternatives (and insights into how shells work).
The answers here do not always contain best practices, so if you just want the directory echoed on the screen (even when it contains spaces):
#!/bin/bash
echo "My Script is being run from here: $(dirname "$0")"
If you want it into a variable and want .
expanded to the full path, you need GNU Readlink first so:
- Install homebrew
Install GNU CoreUtils:
brew install coreutils
Use the following script:
#!/bin/bash szMyPath=$(dirname "$0") if [[ $szMyPath =~ ^. ]]; then szMyPath="$(dirname "$(greadlink -f "$0")")" fi echo "$szMyPath"
-
The second, longer version is giving me an error:
readlink: illegal option -- f
.– murrayAug 24, 2019 at 19:01 -