bash if 语句中的多个一元运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2309849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 21:42:25  来源:igfitidea点击:

Multiple unary operators in an if statement

bashif-statementsyntaxunary-operator

提问by Kiran

Is it possible to have multiple unary operators in if statements.. Here is the code snippet which is giving me error.

if 语句中是否可以有多个一元运算符.. 这是给我错误的代码片段。

Please correct the code here.

请更正此处的代码。

if [ -f $input_file ] -a [ -f $output_file ] -a [ -f $log_file ] ]
then
    ### Some Code here
fi

回答by ghostdog74

if [ -f "file1" -a -f "file2" -a "file3" ]; then
   #some code
fi

回答by Paused until further notice.

If you use Bash's double-bracket, you can do this:

如果你使用 Bash 的双括号,你可以这样做:

if [[ -f "$input_file" && -f "$output_file" && -f "$log_file" ]]

which I find cleaner to read than other options shown here (but that's subjective). However, it has other advantages.

我发现它比此处显示的其他选项更易于阅读(但这是主观的)。但是,它还有其他优点

And, as ghostdog74shows, you should always quote variables containing filenames.

而且,正如ghostdog74所示,您应该始终引用包含文件名的变量。

回答by gregseth

You can see the [ ... ]operator only as a shortcut for test .... The options are used th same way.

您只能将 [ ... ]运算符视为 的快捷方式test ...。这些选项的使用方式相同。

So in your case you could either write the ghostdog74way or :

因此,在您的情况下,您可以编写ghostdog74方式或:

if [ -f $input_file ] && [ -f $output_file ] && [ -f $log_file ]
then
### Some Code here
fi

回答by Ignacio Vazquez-Abrams

[is a command, not part of the ifstatement. As such you should pass it each of the appropriate arguments instead of trying to incorrectly run it as you have.

[是一个命令,而不是if语句的一部分。因此,您应该将每个适当的参数传递给它,而不是像您一样尝试错误地运行它。

if [ arg1 arg2 arg3 arg4 ... ]
then