How to test file permissions using shell script?
10,602
Solution 1
Check info on permissions on directory or a file or a link
stat -L -c "%a %G %U" FILE or DIRECTORY
Solution 2
#!/usr/bin/env bash
FILE="/etc/shadow"
if ! [[ $(stat -c "%A" $FILE) =~ "r" ]]; then
echo "Hello"
fi
exit 0
This will check if the file has read permission instead of checkinf if the file is readable by your current user.
Related videos on Youtube
Author by
Su_scriptingbee
Updated on September 18, 2022Comments
-
Su_scriptingbee almost 2 years
I am testing if my file has read permissions, by running this script as root:
#!/usr/bin/env bash FILE="/etc/shadow" if ! [ -r $FILE ]; then echo "Hello" fi exit 0
Ideally, script has to print
Hello
as there is no Read permission. But, it is not happening.ls -ltrh /etc/shadow ---------- 1 root root 7.1K Jun 7 06:59 /etc/shadow
What needs to be modified in script?
-
deimos about 5 yearsDo you run your script as root? Root will still able to read the files with no read permissions. Just use
ls
ornamei
to read file permissions. -
somethingSomething about 5 years@Su_scriptingbee Works here
[11:16:01][kristjan] ~ ~↓↓$↓↓ bash script.bash Hello
-
deimos about 5 years@somethingSomething because you're not running it as root :D
-
somethingSomething about 5 years@deimos ok cool
-
Su_scriptingbee about 5 years@deimos am running the script as root. Here, I would like to implement ' if a file does not have Read permission'.
-
deimos about 5 years@Su_scriptingbee your current script logic is "Can i read the content of the file?". You need to change it to "Does the file has
r
permission?" or switch from root to a non-privileged user. -
Kusalananda about 5 yearsThe effect of permissions is dependent on the user. Root is not bothered by not having read permissions, and the
-r
test is therefore always true. -
terdon about 5 yearsPlease edit your question and explain that you are not trying to test if you can read the file but are trying to figure out the read permissions. As you can see from the answers, the two are quite different.
-
-
dovka almost 4 yearsThis is great - exactly what I need to save permissions/owner and set them later!