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

前端 未结 5 1657
故里飘歌
故里飘歌 2021-01-29 22:04

I guess I\'m not clear on how to do \"and\" tests. I wanted to make sure an argument existed which was working well with [ -e $VAR ], but it turns out that was also

5条回答
  •  清歌不尽
    2021-01-29 22:34

    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
    

提交回复
热议问题