2
#!/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.

3

Regarding testing whether a "variable is 0", one can use:

if [ "$MYVAR" -eq 0 ] ; then exit ; fi

Or, if you prefer:

if [[ $MYVAR -eq 0 ]] ; then exit ; fi

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. Running exit in a function would cause both the function and its calling script to exit.

  • @d-_-b exit should work. Could you provide more context? – John1024 Dec 29 '13 at 4:28
1
[[ "$1" -eq 0 ]] && { echo "Parameter 1 is empty" ; exit 1; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.