To get the canonical location of a path, use
readlink with the
-e or
-f options.
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.
Code:
#!/bin/bash
#get the canonical path of the script
scriptpath=$( readlink -qne "$0" )
#strip of the filename and cd into the directory
cd "${scriptpath%/*}"
#echo the current directory
echo "$PWD"
exit 0
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.
Code:
for directory in "$HOME" /usr/bin /var/log ; do
(
cd "$directory"
echo "$PWD"
)
done
echo "$PWD"
Notice also the use of the built in
$HOME variable instead of "
~".