-1

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?

  • 3
    Do you run your script as root? Root will still able to read the files with no read permissions. Just use ls or namei to read file permissions. – deimos Jun 7 at 10:50
  • @Su_scriptingbee Works here [11:16:01][kristjan] ~ ~↓↓$↓↓ bash script.bash Hello – somethingSomething Jun 7 at 11:18
  • @somethingSomething because you're not running it as root :D – deimos Jun 7 at 11:20
  • 1
    @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. – deimos Jun 7 at 11:37
  • 2
    Please 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. – terdon Jun 7 at 11:49
1

Check info on permissions on directory or a file or a link

stat -L -c "%a %G %U" FILE or DIRECTORY
1
#!/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.

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.