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.

Share:
10,602

Related videos on Youtube

Su_scriptingbee
Author by

Su_scriptingbee

Updated on September 18, 2022

Comments

  • Su_scriptingbee
    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
      deimos about 5 years
      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.
    • somethingSomething
      somethingSomething about 5 years
      @Su_scriptingbee Works here [11:16:01][kristjan] ~ ~↓↓$↓↓ bash script.bash Hello
    • deimos
      deimos about 5 years
      @somethingSomething because you're not running it as root :D
    • somethingSomething
      somethingSomething about 5 years
      @deimos ok cool
    • Su_scriptingbee
      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
      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
      Kusalananda about 5 years
      The 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
      terdon about 5 years
      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.
  • dovka
    dovka almost 4 years
    This is great - exactly what I need to save permissions/owner and set them later!