0

In a specific folder, I'm trying to count the number of files that have all three user permissions (read/write/execute). I do have files like that in my test folder, but however I try to form the condition, the result is always false.

#!/bin/bash
var="$1"
list=$(ls -d $var/*)
count=0
for x in "$list"
do
        perm="$(stat -c %A $x)"
        if [[ "$perm" == "-rwxrwxrwx" ]];
        then ((count++))
        fi
done
echo "$count"
  • 2
    Note that `for x in "$list"` is innately buggy. For that matter, so is `list=$(ls -d $var/*)`. Use `for x in "$var"/*; do` – Charles Duffy Mar 18 '20 at 15:29
  • That said, to see what your script is doing in practice, run `bash -x yourscript` to run it with trace logs to stderr. Read those logs, and you'll see what the comparison that's actually being run is. – Charles Duffy Mar 18 '20 at 15:30
  • As references for the above assertions, see: [BashPitfalls #1](http://mywiki.wooledge.org/BashPitfalls#for_f_in_.24.28ls_.2A.mp3.29), [ParsingLs](https://mywiki.wooledge.org/ParsingLs), [DontReadLinesWithFor](https://mywiki.wooledge.org/DontReadLinesWithFor). – Charles Duffy Mar 18 '20 at 15:31
  • `for x in "$list"` will assign the entire list to `x` all at once. `for x in $list` is *also* buggy, but in more subtle ways. Use the `for x in "$var"/*` suggested above instead. – Charles Duffy Mar 18 '20 at 15:31
  • Mind you, what I'd *really* use for this job is `find`, which can be told to filter on permissions and thus find files with `777` perms, which AFAICT is what you really want. – Charles Duffy Mar 18 '20 at 15:33
  • 1
    `find "$1" -maxdepth 1 -mindepth 1 -perm -777 -printf '\n' | wc -l` and there you are. Much faster since it doesn't run a separate `stat` subprocess per-file, too. – Charles Duffy Mar 18 '20 at 15:34

0 Answers0