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:
$0expands to the name of the shell or shell scripttest -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,
basenamewill 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
cdwill return0if itsuccessfully navigatesto a directory or1when itfails to navigateto the directorycd "$( dirname "$0" )"will usedirnameto strip the last component from the expanded name and try to navigate to that location- if the above
cdfails, we get the current location using&& pwd.pwdwill 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);
This post is also available in: Greek



Hey , thank you , i am converting some scripts to playbooks and this give me a great help.