Using SUDO in Emacs with Tramp
Using Sudo in Emacs
Do you sometimes need to edit system files in Emacs? Here's how to quickly harness sudo in Emacs.
The Problem
When you need to edit system files, you typically need sudo privileges, but launching Emacs with sudo can cause permission issues with your config files. The solution? TRAMP mode, which is built into Emacs.
Open Files with Sudo
Access files with sudo privileges directly by using this syntax in the minibuffer:
C-x C-f /sudo::/path/to/file
or to browse directories:
C-x d /sudo::/some/directory
For example, to browse /tmp/
with sudo privileges:
C-x d /sudo::/tmp/
You can specify which user to use with sudo:
/sudo:root@rc:/path/to/file
Create Abbreviations
To save typing, consider creating an abbreviation in abbrev-mode. Here's mine:
"sdo" "/sudo:root@rc:/@@" xah-abbrev-ahf
You can also create one to revert to non-sudo use (clear the minibuffer first):
"hme" "/home/yal/@@" xah-abbrev-ahf
xah-abbrev-ahf
gives me the abbreviation without the space
On the @@
see this article from Stack Exchange
Never Type Your Sudo Password Again
For maximum convenience, you can configure sudo never to ask for a password:
1. Set your default editor:
sudo update-alternatives --config editor
2. Edit the sudoers file:
sudo visudo
3. Add this line (replace 'yal' with your username):
yal ALL~(ALL) NOPASSWD: ALL
Note Bene: This reduces security by allowing any process running under your user account to execute commands as root without a password.
That's all for today folks!
Postscript: New in Emacs 31
Added
Michael Albinus (the Tramp maintainer) has shared some exciting additions coming in Emacs 31:
C-x x @
- A new keybinding for tramp-revert-buffer-with-sudo
that lets one instantly reopen the current file with sudo privileges
@
- In Dired mode, this opens the file at point with sudo permissions
Both commands support:
- Using a
C-u
prefix to select alternative Tramp methods beyond sudo - Working with already-remote files (multi-hop capability)
These new keybindings will make working with system files even more convenient than the methods described above.
Thanks to Michael Albinus for sharing these upcoming features.
Comments
To comment, sign in with your GitHub account.