To get the canonical location of a path, use readlink
with the -e
And since scripts run as sub-processes with their own environments, all you generally need to do is cd
into the directory inside the script. When the script exits, you're back in the starting shell's environment.
#get the canonical path of the script
scriptpath=$( readlink -qne "$0" )
#strip of the filename and cd into the directory
#echo the current directory
If you need to operate on multiple directories within a script, you can run groups of commands in (..)
subshells, which will act the same way.
for directory in "$HOME" /usr/bin /var/log ; do
Notice also the use of the built in $HOME
variable instead of "~