if语句中的多个一元运算符[重复]

问题描述 投票:8回答:4

这个问题在这里已有答案:

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

请在此处更正代码。

if [ -f $input_file ] -a [ -f $output_file ] -a [ -f $log_file ] ]
then
    ### Some Code here
fi
bash if-statement syntax unary-operator
4个回答
10
投票
if [ -f "file1" -a -f "file2" -a "file3" ]; then
   #some code
fi

7
投票

如果你使用Bash的双支架,你可以这样做:

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

我发现阅读比这里显示的其他选项更清晰(但这是主观的)。但是,它有other advantages

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


4
投票

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

所以在你的情况下,你可以写ghostdog74方式或:

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

1
投票

[是一个命令,不是if声明的一部分。因此,您应该传递每个适当的参数,而不是试图错误地运行它。

if [ arg1 arg2 arg3 arg4 ... ]
then
© www.soinside.com 2019 - 2024. All rights reserved.