Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
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
up vote 8 down vote accepted

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

share|improve this answer
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
@Gordon - true: My answer is predicated on the sudo portion working :) – voretaq7 Jun 15 '11 at 20:48
if sudo test -f "/path/to/file"; then
    echo "FILE EXISTS"

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"
share|improve this answer
Luca Borrione's answer worked perfectly for me. I needed to test existence of files that were deep inside directories readable only by root. – wallheater Nov 21 '12 at 18:10

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.