Member-only story
Bash
Why bash script does not work on crontab
Recently I met an issue that my shell script does not run in crontab. But when I run them directly it works. For example consider this bash:
#!/usr/bin/env bash
aws ec2 stop-instances --instance-ids i-0cebb331ce02934a i-08c55f40aadfa64e i-09aeaec43de5e67e i-09a63f61a682f8d9 i-049cfae6dd25b799
Works perfectly fine when run
./stop-instances.sh
But when add them to the crontab with crontab -e, it does not work
39 14 * * * /home/cuongld/Tools/aws-scripts/stop-instances.sh
45 13 * * * /home/cuongld/Tools/aws-scripts/start-instances.sh
The problem lies in this:
Because the environment when crontab runs, is different when we run them directly.
So what we need to do is try to make the crontab env is the same as we’re using. My solution is to add the path to the sh files like below:
#!/usr/bin/env bashPATH=/home/cuongld/miniconda3/bin:/home/cuongld/miniconda3/bin:/home/cuongld/.cargo/bin:/home/cuongld/.local/bin ....aws ec2 stop-instances --instance-ids i-0cebb331ce029342 i-08c5f40aadfa64e i-097aeaec435e67e i-09a63f6d682f8d9 i-049cfadd425b799
And that’s it.
Hope it helps guy.
PEACE~~