Bash ternary operation gives same output on either Boolean condition

315 views Asked by At

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.

2

There are 2 answers

2
Etan Reisner On BEST ANSWER

The test [[ $LOG_TO_TERMINAL ]] tests whether LOG_TO_TERMINAL has a value or not. Nothing else. The shell doesn't treat false (or 0 or null etc.) as special false-y values.

If you want some other test you need to test specifically for that.

[[ $LOG_TO_TERMINAL = true ]]

or

[[ $LOG_TO_TERMINAL != false ]]

or

[[ $LOG_TO_TERMINAL = 1 ]]

etc.

If you were expecting to use the return code from the true and/or false 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.

0
Eugeniu Rosca On

You want this:

[[ $LOG_TO_TERMINAL = 1 ]] && echo "log to terminal" || echo "don't log to terminal"