How to handle a missing environment variable set in `crontab`
3
votes
2
answers
305
views
I have a
bash
script that I need to be able to start from either:
1. cron
2. an interactive (logon) shell
This script needs to know whether it was started from cron
, or started from an interactive shell. I thought I had resolved this issue when I declared an environment variable in the root crontab
:
RUN_BY_CRON="TRUE"
In the script, I test RUN_BY_CRON
and use the result to set another variable:
if [ "$RUN_BY_CRON" = "TRUE" ]; then
((wait_time=DELAY_HALT*60))
fi
This worked until I added set -u
to my script (as a *"common defensive programming strategy"*). Since then, when I run the script from the command line, set -u
flags RUN_BY_CRON
as an "unbound variable" error:
$ sudo ./skedrtc.sh
./skedrtc.sh: line 24: RUN_BY_CRON: unbound variable
FWIW, I ran shellcheck
on this script, and got no warning or error.
I tried adding a test for RUN_BY_CRON
, but got the same error. I tried testing for an interactive shell, but testing from within the script itself isn't helpful:
...
if [ -z "$RUN_BY_CRON" ]; then # test for null string
RUN_BY_CRON="FALSE"
fi
...
if [[ $- == *i* ]]; then # test for interactive shell
RUN_BY_CRON="FALSE"
fi
This feels like a [*"catch 22"*](https://www.merriam-webster.com/dictionary/catch-22) situation. I've looked for ways to create a **try-catch** block, but AIUI there's nothing like that in bash
.
### Q: How can I avoid this "unbound variable" error without removing the set -u
?
Asked by Seamus
(3772 rep)
Jan 19, 2025, 11:29 PM
Last activity: Jan 24, 2025, 12:20 AM
Last activity: Jan 24, 2025, 12:20 AM