The correct way to abort an operation from the sudo password prompt

sudo

Sometimes it amazes me the "little" things I don't know about Unix. For years now I have occasionally noted that I don't actually know how to deal with the sudo password prompt cleanly. Every once in a while I sudo something only to realize that I don't actually want to run the command at all. This happens rarely enough I always forget to ask but just often enough that I remember I still haven't learned the right way to abort.

Once sudo starts asking for a password it doesn't want to give up. You can't Ctrl+C it. If you give it the right password it will run the command that I've decided I want to abort. The only solution I have found is to give it wrong passwords until it gives up asking and falls back to an su prompt which actually listens to a Ctrl+C. This feels dirty to me. It's sad enough that I changed my mind about a command; not to be able to cancel it cleanly is just embarrassing.

What is the proper way to tell sudo to abort the attempt while at the password prompt?

Best Answer

What I usually do is Ctrl + Z to suspend the task, then kill %1 or even kill -9 %1 to stop:

> sudo ls
[sudo] password for user:

Ctrl + Z

[1]  +   512 Suspended                     sudo ls
> kill %1
[1]  + Suspended (tty output)        sudo ls
> kill -9 %1
[1]    Killed                        sudo ls

(In case you have more background tasks in your shell: The number you need to give after the percent sign is the one in brackets []).

Related Question