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.