Linux – Check if a file exists, using another user (sudo -u)

bashlinuxsudo

I want to check if a file exists [ -f /path/to/file ] using another user.

So, I added:

USER1        ALL=(USER2)     /bin/mkdir, /usr/bin/git, /bin/echo

to the sudoers file.

The problem is, when I try to execute

USER1:~$ sudo -u USER2 [ -f /path/to/file ] && echo "1"

I get the following:

Sorry, user USER1 is not allowed to execute '/usr/bin/[ -f /path/to/file ]' as USER2 on localhost.

So, the question here is: How do I enable that on the sudoers file?


Solution

I added /usr/bin/test to the sudoers file, and instead of going with this:

USER1:~$ sudo -u USER2 [ -f /path/to/file ] && echo "1"

I actually used:

USER1:~$ sudo -u USER2 /usr/bin/test -f /path/to/file && echo "1"

Best Answer

You're trying to execute /usr/bin/[ but haven't given the user permission to. There are two ways you could do this.

The first is to allow the user to execute /usr/bin/[ (which is the test program). This would allow the user to perform any kind of test on any file. You can also use test instead of [, which may be more obvious as to what's happening.

USER1   ALL=(USER2) /bin/mkdir, /usr/bin/git, /bin/echo, /usr/bin/[, /usr/bin/test

And then run:

sudo -u USER2 [ -f /path/to/file ] && echo "1"

or

sudo -u USER2 test -f /path/to/file && echo "1"

The second option is to write a wrapper script and allow the user to execute that. For example, with the following in /usr/local/bin/exists:

#!/bin/sh
set -e
[ -f "$1" ]

And this in /etc/sudoers:

USER1   ALL=(USER2) /bin/mkdir, /usr/bin/git, /bin/echo, /usr/local/bin/exists

The user could run:

sudo -u USER2 /usr/local/bin/exists /path/to/file && echo "1"