Linux – How to use sudo to check if a file exists

bashlinuxsudo

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.

Best Answer

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