How do I run a sudo command in Emacs? How do I run a sudo command in Emacs? shell shell

How do I run a sudo command in Emacs?


How about:

(shell-command (concat "echo " (shell-quote-argument (read-passwd "Password? "))                       " | sudo -S your_command_here"))


I frequently call commands from Emacs like aptitude update. scottfrazer's solution might not be as useful. Synchronous commands make me wait for a long time, and if you execute an unsupported program (for example, aptitude, which uses ncurses), you will hang up Emacs (C-g won't help), and CPU load will be 100%. Changing to async-shell-command solves this.

But it also introduces a new problem. If your command fails, your password will end up in *Messages* buffer:

echo PASSWORD | sudo -S aptitude: exited abnormally with code 1.

That's why i propose the following solution:

(defun sudo-shell-command (command)  (interactive "MShell command (root): ")  (with-temp-buffer    (cd "/sudo::/")    (async-shell-command command)))

Here "M" in interactive prompts for program name in minibuffer, with-temp-buffer creates a sham buffer, in which we change directory to /sudo::/ to use TRAMP for sudo prompt.

This is the solution by David Kastrup from sudo command with minibuffer password prompt @ gnu.emacs.help.

Note, you still shouldn't call aptitude directly, otherwise the subprocess will be there forever, until you send sudo pkill aptitude.

Read on shells and processes in manual.


If you're running emacs22 or later, you can just start up a shell from emacs and run your sudo command there. It'll automatically pull you into the minibuffer window for your password:

M-x shellsudo whoami

This should just ask for your password down at the bottom of the screen (without displaying it).