Why bash script does not work on crontab

but works when run directly.

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


But when add them to the crontab with crontab -e, it does not work

39 14 * * * /home/cuongld/Tools/aws-scripts/
45 13 * * * /home/cuongld/Tools/aws-scripts/

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 ec2 stop-instances --instance-ids i-0cebb331ce029342 i-08c5f40aadfa64e i-097aeaec435e67e i-09a63f6d682f8d9 i-049cfadd425b799

And that’s it.

Hope it helps guy.


A passionate automation engineer who strongly believes in “A man can do anything he wants if he puts in the work”.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store