如何确定文件在 bash 脚本中是否不可执行

时间:2021-03-09 20:15:04

标签: bash shell

我正在遍历一个目录,需要找到所有不可执行的文件。我知道

if [ -x $dir ]; then 
    echo "$dir is an executable file"
fi

表明它是可执行的,但我该如何做相反的事情?我试过了

if [ !-x $dir ]; then 
    echo "$dir is not-executable"
fi

然而这行不通。

2 个答案:

答案 0 :(得分:3)

通过 Shell Check 运行该行显示:

if [ !-x $dir ]; then
      ^-- SC1035: You are missing a required space here.
         ^-- SC2086: Double quote to prevent globbing and word splitting.

添加缺失的空格和引号导致:

if [ ! -x "$dir" ]; then

您还可以使用通用语法 !if ! command 放在方括号外,该语法适用于任何命令:

if ! [ -x "$dir" ]; then

答案 1 :(得分:2)

要么:

if ! [ -x "$dir" ]; then 
    echo "$dir is not an executable file"
fi

或:

if [ ! -x "$dir" ]; then 
    echo "$dir is not an executable file"
fi

会起作用。通常,任何命令都可以被 ! 否定。因此,如果 cmd 返回非零,则 ! cmd 返回零。 [ 命令也接受 ! 作为参数,因此 [ expression ][ ! expression ] 反转。您的选择几乎是一种风格选择,几乎没有区别。

当然,你也可以这样做:

if [ -x "$dir" ]; then
    :
else
    echo "$dir is not an executable file"
fi