Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.
#!/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.

share|improve this question

2 Answers 2

up vote 2 down vote accepted

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.

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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