if condition and sudo

Hello, I have a regular user account that needs to run a script as a cron job. This script is to check whether or not a file exists, and if so, perform an action on that file using sudo (the file is owned by root). The problem is that the if statement fails, because the user does not have read permissions on the folder.

if [ -f $SOMEFILE ]; then
     sudo cp $SOMEFILE /somewhere/else/
else
  echo $SOMEFILE" not found!"
fi

The "sudo cp" command, when run on its own, works just fine. But the "if -f" condition fails because the user cannot access the folder where $SOMEFILE lives, in order to check if it exists or not.

Is there some way to use sudo in conjunction with the "if -f" condition? Or is there some other command or method I use use with sudo to check for the existence of this file?

Thank you

Remove sudo from the script, include the script on the allowed sudo commands. run the script as:

sudo script

You could also do:

sudo sh -c "[ -f $SOMEFILE ] && cp $SOMEFILE /somewhere/else" || echo "$SOMEFILE" not found!

Problem is this may report "not found" error if the copy fails for some reason (out of diskspace or /somewhere/else is and invalid path).

A better solution is to make another script to copy/report missing $SOMEFILE and run this as root from your cron script.

Thanks for the ideas, I ended up solving it this way:

if sudo test -f $SOMEFILE; then
  sudo cp $SOMEFILE /other/place/
else
  echo $SOMEFILE" not found!"
fi

So "sudo test" works for letting regular users check on files that they normally wouldn't have permission to.