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

前端 未结 5 1656
故里飘歌
故里飘歌 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:44

    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)

提交回复
热议问题