我有三个变量:
VAR1="file1"
VAR2="file2"
VAR3="file3"
如何在if语句中使用和(&&
)运算符如下:
if [ -f $VAR1 && -f $VAR2 && -f $VAR3 ]
then ...
fi
当我编写这段代码时,它会给出错误。什么是正确的方法?
所以为了使你的表达能够起作用,改变&&
的-a
就可以了。
这是正确的:
if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
then ....
或者喜欢
if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
then ....
甚至
if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
then ....
你可以在这个问题bash : Multiple Unary operators in if statement和What is the difference between test, [ and [[ ?那里给出的一些参考资料中找到更多细节。