How to check if the “sudo” permission will be necessary to run a command

permissionssudo

Is there a way to determine easily whether I can read or write to/from a given file, or whether I will need to use "sudo" to do so? Running commands unnecessarily as sudo means that those files get created with the root user as owner, which is undesirable.

Something like

is_readable /path/to/file
if [[ $? == 0 ]]; then
    do_command /path/to/file;
else
    sudo do_command /path/to/file;
fi

Best Answer

You can try the -w switch of the test utillity:

[ -w /path/to/file ] && do_command /path/to/file || sudo do_command /path/to/file

Or the long version:

if [ -w /path/to/file ]; then
  do_command /path/to/file 
else
  sudo do_command /path/to/file
fi

From the manpage

-w FILE
              FILE exists and write permission is granted
Related Question