0

I'm learning shell scripting and I am writing a script which lists the file for which the user has "7" permission, i.e. "rwx". So far I've written this:

for F in *
do
        a= $(stat -c "%a" "$F")
        echo $a
        if ((b==7))
        then
                echo $F
        fi
done

Here the value of a is "1". What am I doing wrong here?

5

In shell, spaces matter. Replace

a= $(stat -c "%a" "$F")

With:

a=$(stat -c "%a" -- "$F")

(also adding the -- option delimiter so the command still works for file names that start with -)

or

a=$(stat -Lc "%a" -- "$F")

if for symlinks, you want the permissions of the target of the symlink (since on most systems, the permissions of the symlink itself are not relevant).

Example

To make things simple, let's just run the stat command on a single file and we'll do it at the interactive command line:

$ stat -c "%a" file
660

Now, let's try the command with the space:

$ a= $(stat -c "%a" file)
bash: 660: command not found
$ echo a=$a
a=

We get an error message and a is not set to a new value. (If, as in your case, a had previously been assigned to 1, it would stay unchanged at 1.) Now try without spaces:

$ a=$(stat -c "%a" file)
$ echo a=$a
a=660

This works. a is successfully set to the number returned by the stat command.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.