#!/bin/bash
if [[ -n "$MYVAR" ]]; then exit; fi
# otherwise the rest of the script continues...
I'm trying to exit out of a shell script if a certain ENV variable is 0. The script above does not seem to work (I've also tried using return
instead of exit
.
Can someone explain how this would be done, or what's wrong with the line above?
When I type that in my terminal (replacing exit with echo "YES"
it works just fine.
Best Answer
Regarding testing whether a "variable is 0", one can use:
Or, if you prefer:
The expression
[[ -n "$MYVAR" ]]
tests for a non-empty string value of MYVAR. The string "0" is non-empty: it has one character, the same as the string "1".exit
will cause the script to exit.return
, by contrast, is used in functions or sourced scripts when you want to quit the function or sourced script but continue with execution of the calling script. Runningexit
in a function would cause both the function and its calling script to exit.