Bash Scripts – Using Absolute Path in Bash Scripts

bashcronlinuxshell

I've got a shell script myscript.sh which calls a command, let's say mycmd.
When i run that script from the terminal, e.g. ./myscript.sh, everything works fine.

But when i add that script to the crontab, the output of mycmd is empty. When i call /usr/local/bin/mycmd inside of myscript.sh everything works fine again.

So why i have to use the absolute path of the executable? Is it because it is not in the $PATH of the "cron-bash"?

Best Answer

You have it exactly right - the environment of cron may have a PATH that does not include /usr/local/bin/. You can fix this by, in your script, appending that directory to the PATH:

PATH="$PATH:/usr/local/bin/"

The best practice, though, is indeed to use explicit paths for all external binaries that a script calls just in case (for instance) a maliciously designed program conveniently called cp gets dropped into the PATH somewhere before /bin.

Related Question