Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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
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
add comment

2 Answers

up vote 4 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
3  
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
add comment
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
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
add comment

Your Answer

 
discard

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.