bash - 检查目录是否为/Library或/Public

标签 bash

我正在尝试编写一个 bash 脚本,该脚本采用用户主目录并循环遍历第一级子目录,并且仅当这些目录不是/Library 或/Public 文件夹时才对这些目录执行一些维护。到目前为止,我的代码不起作用,因为我收到一条错误消息,指出 $dir 返回的目录名称是一个目录。这是代码:

#!/bin/bash

user="short name"
source_root="/Users/"

source_use="$source_root$user"
cd "$source_use"

dirarr=( */ )

echo ${dirarr[@]}

for dir in "${dirarr[@]}"
do 
    if ( "$dir" -ne "/Library" -o "$dir" -ne "/Public")
        then echo $dir.
            # do something
    fi
done

任何人都可以帮我完成这个工作吗?

非常感谢

最佳答案

您的脚本有几个问题:

  1. 您需要使用[ ][[ ]]在你的if声明,而不是 ( ) 。在您的示例中 ( )创建一个子 shell 并尝试运行命令 "$dir" ,这就是您收到错误消息的原因。

  2. 您正在与找不到的字符串进行比较 - 尝试 "Library/""Public/"相反。

  3. 您可能想要 -a而不是-o

  4. -ne用于比较数字。您想要!= .

这是脚本的更正版本:

#!/bin/bash

user="short name"
source_root="/Users/"

source_use="$source_root$user"
cd "$source_use"

dirarr=( */ )

echo ${dirarr[@]}

for dir in "${dirarr[@]}"
do 
    if [ "$dir" != "Library/" -a "$dir" != "Public/" ]
    then
        echo $dir.
        # do something
    fi
done

关于bash - 检查目录是否为/Library或/Public,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13982039/

相关文章:

bash - 从 bash 中的 csv 文件中删除第一个逗号

bash - Bash 中的表达式递归级别超出错误

bash - 使用 popd、pushd 时获取我的目录堆栈中不同目录路径的引用

linux - bash:上次访问的路径是否有任何类型的缓冲区?

bash - 如何在 Bash 中重命名关联数组?

mysql - 将 MySQL "SELECT"查询传递给 shell 变量

mysql - 发送 10GB mysql 表到远程服务器

bash - 通过 sbatch 传递命令行参数

windows - Windows Cmd 中的 Cygwin Bash 未运行可执行文件

string - 并行命令中的 bash 字符串替换