Nick Zagkanas
Nick Zagkanas

Reputation: 89

Comparing the permissions(octal) of files with an integer in Bash Shell

I'm in a bit of trouble during my shell script. I have this code until now.

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

When I run it on the terminal, I can see that my computer asks for access(which means that I have done well until now. The whole idea is that I search for files' permission and I compare this permission in the octal system with a given number($first). In the end, it shows nothing and the script is looping from the start.

Any help would be great.

Upvotes: 1

Views: 609

Answers (1)

Léa Gris
Léa Gris

Reputation: 19545

You can replace this script by:

#!/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

Upvotes: 6

Related Questions