Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash conditionals: how to "and" expressions? (if [ ! -z $VAR && -e $VAR ])

Tags:

bash

shell

People also ask

How do you use multiple IF statements in shell script?

To use multiple conditions in one if-else block, then elif keyword is used in shell. If expression1 is true then it executes statement 1 and 2, and this process continues. If none of the condition is true then it processes else part.

What does == mean in bash?

== is a bash-specific alias for = and it performs a string (lexical) comparison instead of a numeric comparison.

What is the difference between the == and comparison operator when used in bash?

In shell scripting, = and == are for string comparisons and -eq is for numeric ones. So, when comparing the strings, use = or == (depending on which shell you are using, sh or bash ), while to check for equality between integers, use -eq comparison operator.


if [ ! -z "$var" ] && [ -e "$var" ]; then
      # something ...
fi

From the bash manpage:

[[ expression ]] - return a status of 0 or 1 depending on the evaluation of the conditional expression expression.

And, for expressions, one of the options is:

expression1 && expression2 - true if both expression1 and expression2 are true.

So you can and them together as follows (-n is the opposite of -z so we can get rid of the !):

if [[ -n "$var" && -e "$var" ]] ; then
    echo "'$var' is non-empty and the file exists"
fi

However, I don't think it's needed in this case, -e xyzzy is true if the xyzzy file exists and can quite easily handle empty strings. If that's what you want then you don't actually need the -z non-empty check:

pax> VAR=xyzzy
pax> if [[ -e $VAR ]] ; then echo yes ; fi
pax> VAR=/tmp
pax> if [[ -e $VAR ]] ; then echo yes ; fi
yes

In other words, just use:

if [[ -e "$var" ]] ; then
    echo "'$var' exists"
fi

if [ -n "$var" -a -e "$var" ]; then
    do something ...
fi

 


Simply quote your variable:

[ -e "$VAR" ]

This evaluates to [ -e "" ] if $VAR is empty.

Your version does not work because it evaluates to [ -e ]. Now in this case, bash simply checks if the single argument (-e) is a non-empty string.

From the manpage:

test and [ evaluate conditional expressions using a set of rules based on the number of arguments. ...

1 argument

The expression is true if and only if the argument is not null.

(Also, this solution has the additional benefit of working with filenames containing spaces)