linux - 测试条件shell脚本

标签 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 期待二元运算符不是 '!=' 很奇怪?
有人可以告诉我我做错了什么以及为什么吗?


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

最佳答案

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

if [[ -d "DIR2" ]];

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

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

关于linux - 测试条件shell脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33048526/

相关文章:

linux - 如果之后使用管道,为什么 wait 会生成 “<pid> is not a child of this shell” 错误?

linux - gnome-terminal 命令可以从命令行运行,但不能从 Cinnamon 快捷方式(或脚本)运行

linux - 如何在 shell 脚本中使用 sed 从文件的每一行中删除单词?

json - 在 shell 脚本中使用 jq 过滤器从 stringify 对象获取 json 对象

linux - 使用 ffmpeg 截取多个屏幕截图

c++ - 通过管道传递整数

linux - 尝试编写一个shell脚本来监视Linux中的服务何时停止,并自动重新启动该服务

linux - 是否可以对文件夹应用计数功能,然后在文件夹超出限制时删除文件?

linux - 如何为 Linux 内核开发做出贡献?使用最新的源代码?

bash - PIG-如何将Shell命令用于模式文件/文件夹名称