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