测试条件shell脚本

时间:2015-10-09 23:26:14

标签: linux bash shell unix

所以我正在编写一个脚本,在执行之前必须检查文件是否存在。我有以下代码:

if [[ \( -d "DIR2" \) != true ]];
then
    echo "nonexistent dir"
    exit 1
elif [[ \( -d "DIR1" || -f "DIR1" \) != true ]];
then
    echo "nonexistent dir or file"
    exit 1
fi

我似乎对括号做错了,因为我得到以下内容:

./syncdir.sh: line 11: conditional binary operator expected
./syncdir.sh: line 11: syntax error near `-d'
./syncdir.sh: line 11: `if [[ \( -d "DIR2" \) != true ]];'

我觉得奇怪的是,bash期望二元运算符不是'!='一个? 有人可以告诉我我做错了什么,为什么?

我真的对括号感到困惑,我仍然没有掌握它。

1 个答案:

答案 0 :(得分:2)

您的条件语法完全错误。它应该是:

if [[ -d "DIR2" ]];

if [[ ! ( -d "DIR1" ||  -f "DIR1" ) ]];

如果条件表达式中有括号,则不需要转义它们(只有在您使用[命令时才需要它们)。而且您不需要与truefalse进行比较。