28

Is it possible to test effective permissions of a file for a specific user?

I normally do this by su user and then accessing the file, but I now want to test this on an user with no shell (i.e. a System user)

4 Answers 4

33

I found convenient to use in scripts something like

 sudo -u <user> test -r <file-to-test> && ...
2
  • 4
    best answer, as you can test for readable (-r), writable (-w) and executable (-x) without actually modifying/creating the file. man test for more details
    – Thomas BDX
    Jul 1, 2014 at 18:18
  • And lends itself wonderfully to use in scripts, where you generally need things to be non-interactive.
    – Erathiel
    Feb 9, 2023 at 13:42
25

The sudo command can run anything as a particular user with the -u option. Instead of worrying about shells, just try to cat (or execute, whatever) your file as your target user:

$ sudo -u apache cat .ssh/authorized_keys 
cat: .ssh/authorized_keys: Permission denied
2
  • 1
    cat is probably not the best choice though... it you are testing a large file or a binary file... Nov 14, 2015 at 6:29
  • Your example is flawed though; SSH requires particular permissions set on .ssh (u=rwx,g=,o=) and its children (u=rw,g=r,o=r) or it will refuse to use the entire config for that user. This does not test that.
    – detly
    Sep 13, 2020 at 23:35
18
sudo -u <user> test -r <file-to-test>; echo $?

The echo $? part will output the exit status from the test.

Just remember here that the output will be 0 if the operation was successful! Or non-zero, e.g. 1, if not.

Like @Thomas's comment on @user72025's answer, use man test to get more operation tests, like test -x to test executability, test -w for writability, etc.

1
  • 2
    For me, this is the most helpful answer. The one by user72025 was close, but I had no idea what the result was. You've made that clear. Thanks. Voting up.
    – inspirednz
    Feb 15, 2018 at 2:41
6

I've found you can use su -s <shellname> <username> to enter a specific shell as a specific user. You can then test file permissions as usual.

E.g.:

su -s /bin/bash Debian-exim
touch /etc/exim4/exim4.conf.template
1
  • Very interesting option.
    – Alex
    Mar 5, 2019 at 8:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .