The command sudo !!
in shells such as zsh
or bash
that implement csh-style history expansion would re-execute the most recent command but prefix it with sudo
. If the most recent command was opening a text editor, then this will be done as the root user. You could then go on and re-do the changes and save. However, the changes that you introduced the first time around would be lost.
Assuming you are using the nano
editor as a non-root user, and you find yourself needing to save the current file as root. You may then do so by filtering the current buffer's contents through sudo tee some/file/path
. That command would run tee
as root and would overwrite or create the file at some/file/path
.
From the nano
editor, you could invoke this filter by pressing ^R^X
, i.e., Ctrl+R+Ctrl+X, and then type
|sudo tee some/file/path
(The initial |
signals to nano
that you want to pass the current document to that command.)
If sudo
needs to prompt you for your password, it will do so. This will mess up the display a bit, but you may redraw the screen by pressing ^L
(Ctrl+L).
Note that care must be taken to specify the correct pathname of the file that you want to write to, as it would irreversibly overwrite that file with the contents of the editor's buffer. Since you write as root, permissions will not stop you from destroying data. This is therefore a sort of "hack" that may possibly be good to know about, but that you don't want to rely on.
The ability to filter text from nano
to an external command like this was added in release 2.9.8 (2018).
nano
, is that what you use? Please edit and clarify.mv
it afterwards. At least saves me from having to make the changes twice.sudo mv /tmp/file to /realpath/file
. Check permissions and ownership afterwards.