"command not found" when running a script via cron
To avoid having to type the absolute path to a command, shells introduced the $PATH
environment variable, each directory is separated by a :
and searches are done from left to right. cron
often clears the whole environment, including this $PATH
variable. Therefore, the script may behave differently in your cron compared to the behavior in the shell.
Use absolute paths
Run which db2
as db2inst1
user to get the full path for the db2
program. If the output is /usr/bin/db2
, your cron command would look like:
/usr/bin/db2 connect to myDB2
Set the PATH variable
Run echo "$PATH"
as db2inst1
user to get the $PATH
variable and make sure this variable is available in your cron script too. For example, if the output was /usr/local/bin:/usr/bin:/bin
, you would put the next line in the top of your shell script:
export PATH="/usr/local/bin:/usr/bin:/bin"
As answered in https://askubuntu.com/a/23438/227839, you should set PATH
in your shell script:
#!/bin/bash
PATH="/usr/local/bin:/usr/bin:/bin"
# rest of script follows
or in the crontab file, which will apply to all cron jobs:
PATH="/usr/local/bin:/usr/bin:/bin"
0 1 * * * db2 connect to myDB2
You must define what db2 and myDB2 are, otherwise use the absolute location of 'file' or 'application' which want to run.
Example:
/bin/rm /home/ubuntu/a.txt