在 Bash Shell 中将文件的权限(八进制)与整数进行比较

Nic*_*nas 1 unix permissions bash shell terminal

我在执行 shell 脚本时遇到了一些麻烦。直到现在我都有这个代码。

echo "Give directory name"
read  dirname;
if [ -d "$dirname" ]; then
    for filename in "$dirname"/*
    echo "Files found: $(find "$dirname" -type f | wc -l)"
    do
        if [ $(stat -f "%a" "$filename") == "$first" ]; then
        echo "Files with ($first) permission is: $filename"
        fi
    done

fi
Run Code Online (Sandbox Code Playgroud)

当我在终端上运行它时,我可以看到我的计算机要求访问(这意味着我到目前为止做得很好。整个想法是我搜索文件的权限并将八进制系统中的此权限与给定数字($first)。最后,它什么也没显示,脚本从头开始循环。

任何帮助都会很棒。

Léa*_*ris 6

您可以通过以下方式替换此脚本:

#!/usr/bin/env bash

read -r -p $'Give directory name:\n' dirname
if [ -d "$dirname" ]
then
    read -r -p $'Give expected octal permissions:\n' first
    mapfile -d '' -t files < <(
      find "$dirname" -maxdepth 1 -type f -perm "$first" -print0
    )
    if [ "${#files[@]}" -gt 0 ]
    then
      printf 'Found: %d files with the (%s) permission in %s:\n' "${#files[@]}" "$first" "$dirname"
      printf '%s\n' "${files[@]}"
    else
      printf 'Found no file with the (%s) permission in %s\n' "$first" "$dirname"
    fi
fi
Run Code Online (Sandbox Code Playgroud)