I have a bash
script that I need to be able to start from either:
cron
- 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" situation. I've looked for ways to create a try-catch block, but AIUI there's nothing like that in bash
.
echo ${var1:-tmpValue} ${var2:=DefaultValue}; echo ${var2:+AlternateStr${var2}} ; echo ${var4:?UnsetErrrMsgs} ; echo "${var1} ${var2} ${var3}"
? They may help.