So in my bash script, I output status report to terminal as well as write it to the log file. I wanted to use a bash ternary operator that will output to terminal as well as write a log file if variable LOG_TO_TERMINAL
is true, and if that is set to false, just write to a log file without outputting status to the terminal.
My sample code looks like this:
[[ $LOG_TO_TERMINAL ]] && echo "error message" >> $LOG_FILE || echo "error message" | tee -a $LOG_FILE
which just logs the file instead of echoing to the terminal no matter whether I set LOG_TO_TERMINAL
to true
or false
.
To isolate the problem, I tried simplifying the code to:
[[ $LOG_TO_TERMINAL ]] && echo "log to terminal" || echo "don't log to terminal"
But this code snippet also echoes "log to terminal" no matter what its value is.
The test
[[ $LOG_TO_TERMINAL ]]
tests whetherLOG_TO_TERMINAL
has a value or not. Nothing else. The shell doesn't treatfalse
(or0
ornull
etc.) as special false-y values.If you want some other test you need to test specifically for that.
or
or
etc.
If you were expecting to use the return code from the
true
and/orfalse
commands then you need$LOG_TO_TERMINAL && Y || Z
or similar to run the command stored in the variable (though I wouldn't recommend this version of this test).Also note that
X && Y || Z
is not a ternary operation in the shell. See the Shellcheck wiki for warning SC2015 for more about this.