Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm not sure if sudo supports so, I want to execute a command, only if this command is configured as NOPASSWD, that is, if the command can be run without password, run it; Otherwise quit directly.

So far the only option seems to be listing all available commands with sudo -l and parse the output manually, that looked dirty.

Are there any alternatives?

share|improve this question
up vote 3 down vote accepted

Not very pretty, but short of parsing sudo -l as you're doing I don't know an alternative: simply run your command with the -n switch:

The -n (non-interactive) option prevents sudo from prompting the user for a password. If a password is required for the command to run, sudo will display an error message and exit.


me$ sudo -l 
User me may run the following commands on this host:
    (ALL) NOPASSWD: /usr/bin/vim
    (ALL) /usr/bin/nano
me$ sudo -n nano /etc/hosts
sudo: a password is required
me$ echo $?
me$ sudo -n vim /etc/hosts
# :q
me$ echo $?

Problem with this is that you can't tell directly from the exit code if sudo failed because it required a password, or if the command you ran failed. So you'll need to parse the output. (Fortunately the error message is static, so that shouldn't be too hard. Beware of localization though.)

share|improve this answer
+1 for localization! – warl0ck Mar 31 '13 at 7:04
I would like to add that allowing vim as root without password is horrible security-wise. – David Kohen Mar 31 '13 at 9:07
Indeed. One can bring up a root shell with an instance of vim running as root by using the :sh command. Also, one could easily modify a root-owned script to start a root shell. Also be careful when running less as root, which allows users to bring up root shell prompts like so: :!sh. – Evan Teitelman Mar 31 '13 at 13:52

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.