6

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
1

2 Answers 2

6

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
1

is_readable /path/to/file is spelled test -r /path/to/file or [ -r /path/to/file ] or [[ -r /path/to/file ]]. See using single or double bracket - bash for how they differ. is_writable uses -w.

Not being able to access a file is not a very good indicator of “needing sudo”. It may be that you should run as a different user or group, not as root. It may be that on a particular system, the way to gain root access is not to run sudo but some other mechanism (su, calife, …). Testing access to a file is fine on a known system with a known configuration. If you distribute scripts that do this, keep in mind that this is only a heuristic, not a reliable test, and let the user easily override your decisions.

Note that just because a file tested as readable doesn't mean you'll actually be able to read it. The permissions on the file may have changed in the meantime. There are sometimes discrepancies between what the file permissions say and what the access checks actually do: remote filesystems with fancy attributes that the local filesystem doesn't understand, security frameworks such as SELinux, etc.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .