Bash: Different behaviour when executed via cron
From FVue
Contents
Problem
When a bash program is executed via cron, it has no terminal connected to stdin/stdout. For instance, I experienced dar to return a different exit status unless the -Q option was specified.
Solution 1. Use env command
You can use env
to simulate an empty environment:
env - ./myscript.sh
Or you can copy the cron environment by first executing a cronjob which copies the cron environment:
55 09 * * * env > ~/cronenv
and then use it like this:
env - $(cat ~/cronenv) ./myscript.sh
See also
- bash - How to simulate the environment cron executes a script with? - Stack Overflow
- Stack Overflow article with same question
Solution 2. Use batch command
Test the program via the batch command. This batch command executes commands just like cron – with no terminal connected, but at a later time when system load levels permit. Using batch saves you the hassle of modifying crontab for just a test-run.
You can install batch via the at package:
sudo apt install at
Example
$ batch warning: commands will be executed using /bin/sh at> touch /tmp/now~ at> ^D $ ls -l /tmp/now~ -rw-r--r-- 1 user group 0 2007-11-15 21:26 /tmp/now~ $
Advertisement