The following code will populate the variables SCRIPT_NAME and SCRIPT_DIR with the name of the script currently being execute and the location this script is in:
SCRIPT_NAME=$(basename $(test -L "$0" && readlink "$0" || echo "$0"));
SCRIPT_DIR=$(cd $(dirname "$0") && pwd);
Notes for SCRIPT_NAME:
$0 expands to the name of the shell or shell script
test -L "$0" checks that input is a file that exists and is a symbolic link
&& readlink "$0" will be executed if the above statement is true and it will print the resolved symbolic link
|| echo "$0" will be executed if the test for symbolic link fails
- finally,
basename will strip directory and suffix from whatever is returned from the above statements
Notes for SCRIPT_DIR:
- Will not resolve the correct folder if the last component of the path is a symbolic link (symlink). It will return the location of the symlink instead of the location of the file the symlink is pointing to
cd will return 0 if it successfully navigates to a directory or 1 when it fails to navigate to the directory
cd "$( dirname "$0" )" will use dirname to strip the last component from the expanded name and try to navigate to that location
- if the above
cd fails, we get the current location using && pwd. pwd will print name of current/working directory
In case you have a problem with $0, it is overwritten or the above function is called by a child script in another folder you can replace $0 with ${BASH_SOURCE[0]}.
SCRIPT_NAME=$(basename $(test -L "${BASH_SOURCE[0]}" && readlink "${BASH_SOURCE[0]}" || echo "${BASH_SOURCE[0]}"));
SCRIPT_DIR=$(cd $(dirname "${BASH_SOURCE[0]}") && pwd);