How can I use sudo to check if a file exists?

Solution 1:

if sudo test -f "/path/to/file"; then
    echo "FILE EXISTS"
else
    echo "FILE DOESN'T EXIST"
fi

test man page

To complete things, on the opposite side, if you want to check from root if a file or directory is readable for a certain user you can use

if sudo -u username test -f "/path/to/file"; then
    echo "FILE EXISTS"
else
    echo "FILE DOESN'T EXIST"
fi

Solution 2:

What you're describing should work fine - as long as you're using absolute paths, and -f ("File exists and is a regular file") is really the test you want to perform.

I see a trailing / in what you posted in your question - Are you testing for a directory? That should be -d, or simply -e ("Something exists with that name - regardless of type")

Also note that unless something along the way is not readable test ([) should be able to tell you if a file owned by root exists or not (e.g. [ -f /root/.ssh/known_hosts ] will probably fail, because the /root/.ssh directory isn't (or at least shouldn't be) readable by a normal user. [ -f /etc/crontab ] should succeed).


Solution 3:

Adding to the other answers, distinguishing between the test or sudo authentication failing could be done by first running sudo true. Most sudo implementations I know of won't require re-authentication within a short period.

For example:

if sudo true; then
    if sudo test -f "/path/to/file"; then
        echo "FILE EXISTS"
    else
        echo "FILE DOESN'T EXIST"
    fi
else
    echo "SUDO AUTHENTICATION FAILED"
fi

Tags:

Linux

Bash

Sudo