Bash scripts runs on command line but errors on cron

Problem

I have a bash script that is supposed to start a docker service using docker compose. When I run it on the commond line it runs ok but when I run it on cron, I would get an error, command not found:


line 21: up: command not found

Solution

As suggested on this ubuntu forum, first check the environment variables that cron adds to a cronjob by setting this cronjob:


* * * * * env > /tmp/env.output

Once the file if generated, you’ll see something similar:


imela@whiscardz:~$ cat /tmp/env.output

1 LC_TIME=en_US.UTF-8
6 PATH=/usr/bin:/bin
....
12 SHELL=/bin/sh
....
18 LC_PAPER=en_US.UTF-8

Notice that the PATH variable has very few locations, therefore

From your command line:


imela@whiscardz:~$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games

Add this PATH to the top line of your bash script:


#!/bin/bash

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games

....

Test running the script on cron and it should now work.

References

Why crontab scripts are not working?

Shell script issue when added to cron

Script doesn’t run via crontab but works fine standalone

Bash script not executing from crontab

bash script running from cronjob command not found

command not found” when running a script via cron