20

I want to check if a file exists like so

[ -f /path/to/file/ ]

However I am running this command as a regular user and the file is owned by root. How can I use sudo to accomplish this.

sudo [ -f /path/to/file/ ] does not work.

voretaq7
  • 79,879
  • 17
  • 130
  • 214
ckliborn
  • 2,778
  • 4
  • 25
  • 37
  • 2
    It does work on my system. What are the symptoms ? Are you sure you want to use -f, not -e ? – b0fh Jun 15 '11 at 15:48

4 Answers4

26
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
magnetik
  • 247
  • 2
  • 12
Luca Borrione
  • 755
  • 2
  • 9
  • 16
12

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).

voretaq7
  • 79,879
  • 17
  • 130
  • 214
  • 5
    There is a possible problem: if the `sudo` command fails (bad password, not allowed in /etc/sudoers, etc), it'll give the same result as if the file didn't exist. – Gordon Davisson Jun 15 '11 at 20:05
  • 1
    @Gordon - true: My answer is predicated on the `sudo` portion working :) – voretaq7 Jun 15 '11 at 20:48
2

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
womble
  • 96,255
  • 29
  • 175
  • 230
0

I just wanted to through this out there since its how I tend to do it

if [ $(sudo ls /etc/ | grep -ic '^wsl.conf$') -gt 0 ]; then ... fi

I like that way as its a bit explicit and I find it should 100% work. I have had issues where if I didn't have the right permissions just using -f always failed

Ron
  • 109
  • 1