The shell always knows the path to the script under normal circumstances, because it's had to read it. Note that there are circumstances where this is not true, for example with setuid scripts on the OSes that support them (not Linux) — but setuid shell scripts are a bad idea anyway. Most importantly, the script may have been moved between the time the shell opened it and the time you try to do anything with it. So only use the path to the script when there is no security or reliability concern in doing so. A software package with a known structure is a valid use case.
The path to the script that was passed to the shell interpreter is available in the special parameter $0
. This may be a relative path, so if you're going to use it, do that before changing to another directory. You can use it if you know that the script won't have been moved in the meantime.
Since $0
may be a symbolic link, you'll need to get its target. There's no POSIX way to do this, but on Linux (GNU coreutils or BusyBox) and recent BSD you can use readlink -f
to get a canonical absolute path.
script_path_in_package=$(readlink -f -- "$0")
script_directory=${script_path_in_package%/*}
Note that this restricts the ways in which you can structure your package. For example, you can't put the script in an architecture-independent directory tree, and link to it inside every architecture-specific directory tree.
readlink
from the coreutils package? – manatwork Oct 09 '12 at 13:54/home
or/raid/archive
) from a config file or pass it in as an argument. There are other options too - for example, you could put thecd
right in your crontab. – jw013 Oct 09 '12 at 14:13/etc/sysconfig/appname
) and parse that from your script. – Nils Oct 11 '12 at 20:28