Here is the best answer I think. It solves a lot of problems not solved in the other answers, namely:
realpathcan find the absolute path from a relative path, and will expand symbolic links (userealpath -sinstead to NOT expand symbolic links)"${BASH_SOURCE[-1]}"is cleaner and shorter than"${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}", and allows this to work whether the script is run OR sourced, and even if the script being called gets called from within another bash function.- I also demonstrate obtaining the script directory and filename, as shown below.
FULL_PATH_TO_SCRIPT="$(realpath "${BASH_SOURCE[-1]}")" # OR, in case of **nested** source calls, it's possible you actually want # the **first** index: # FULL_PATH_TO_SCRIPT="$(realpath "${BASH_SOURCE[0]}")" # OR, use `-s` to NOT expand symlinks: # FULL_PATH_TO_SCRIPT_KEEP_SYMLINKS="$(realpath -s "${BASH_SOURCE[-1]}")" SCRIPT_DIRECTORY="$(dirname "$FULL_PATH_TO_SCRIPT")" SCRIPT_FILENAME="$(basename "$FULL_PATH_TO_SCRIPT")" # Now print it all out echo "FULL_PATH_TO_SCRIPT = \"$FULL_PATH_TO_SCRIPT\"" echo "SCRIPT_DIRECTORY = \"$SCRIPT_DIRECTORY\"" echo "SCRIPT_FILENAME = \"$SCRIPT_FILENAME\"" For a lot more details on this, including some notes on nested source calls and which index you may want from the BASH_SOURCE array, see my main answer on this in the first reference link just belowthe first reference link just below.
References:
- My main answer on this: Stack Overflow: How can I get the source directory of a Bash script from within the script itself?
- How to retrieve absolute path given relative
- taught me about the
BASH_SOURCEvariable: Unix & Linux: determining path to sourced shell script - taught me that
BASH_SOURCEis actually an array, and we want the last element from it for it to work as expected inside a function (hence why I used"${BASH_SOURCE[-1]}"in my code here): Unix & Linux: determining path to sourced shell script man bash--> search forBASH_SOURCE:BASH_SOURCEAn array variable whose members are the source filenames where the corresponding shell function names in the
FUNCNAMEarray variable are defined. The shell function${FUNCNAME[$i]}is defined in the file${BASH_SOURCE[$i]}and called from${BASH_SOURCE[$i+1]}.