Sometimes it is useful to switch into the directory of the script e.g. when we need to call or include further files and don’t want to go through the hassle of searching for the script in the file system. Especially when symlinks are involved everything get a bit more interesting. This little snippet switches into the directory of the script, using readlink to dereference symlinks if the script is called via a symlink.
1 2 3 4 5 6 7 8 9 | ## a small snippet to switch into script directory SCRIPTDIR=${0} if [[ -L ${SCRIPTDIR} ]] then # dereference the symlink SCRIPTDIR="$(readlink -e ${0})" fi # chop off the scriptname and switch into the directory cd ${SCRIPTDIR%/*} |