How can I tell if I have permission to run a particular command?

The simplest case is that of a binary executable like gzip. First, we locate the executable:

$ which gzip
/bin/gzip

Then we look at the attributes of this file:

$ ls -l /bin/gzip
-rwxr-xr-x 1 root root 98240 oct 27  2014 /bin/gzip

The three x's tell us that the file may be executed by the owner (the first root), or anyone in the group root (second root) and anyone else, respectively. So your user is allowed to execute the program.

However, your executable may be a script file that calls other executables inside. You may be able to execute the script but not the programs called inside of it. There is no way to determine if your user is allowed to do that, other than actually trying it out.

Then there are special cases like shutdown - this is really a symbolic link to a core utility called systemctl, which has its own mechanisms to determine whether you are allowed to call it, and to ask you for your sudo password if you don't, for instance.

(About the which command: this locates executables in your $PATH that you are allowed to execute, and tells you which one you use if you have more than one with the same name in the $PATH. It does not locate just any executable. I use it here as an example of where to look for the permission. The fact that which finds the executable already indicates that you have permission to execute it.)


With sudo:

$ sudo -l shutdown
/sbin/shutdown

If I didn't have permission, sudo will complain instead of showing the command.

With polkit, you check for the action you want to run:

$ pkcheck --action-id org.freedesktop.login1.power-off --process $$ -u --enable-internal-agent && echo yes
polkit\56temporary_authorization_id=tmpauthz1
yes

Finding the relevant action is a different question.


You can use:

test -x $(command -v shutdown) && echo yes || echo no

command -v shutdown returns the path to the shutdown command. test -x checks if that path is executable to you.

Note that though you might be able to execute the command, the command may still fail because it has inadequate permission to carry out the task. This is the common case on Unix-type systems, which rather than restricting access to execute a command, instead restrict access on the operations that programs can actually do.