Ok so this happens to me all the time. There has to be a better solution. Let's say you do vim /etc/somefile.conf
and then you do i
but realize you are not sudo
and you can't write. So then I lose my changes by doing :q
then sudo !!
and make my changes again. Is there a better way to do this?
By typing Ctrl+X nano exits and if your file needs change you will be prompted to save the changes in which case to save you should press Y and then enter to save changes in the same file you open. If you are not using any gui and you just want to leave the shell the command is Ctrl+D.
To save a file, you must first be in Command mode. Press Esc to enter Command mode, and then type :wq to write and quit the file. The other, quicker option is to use the keyboard shortcut ZZ to write and quit.
Try
:w !sudo tee "%"
The w !
takes the entire file and pipes it into a shell command. The shell command is sudo tee
which runs tee
as superuser. %
is replaced with the current file name. Quotes needed for files that have either spaces or any other special characters in their names.
Depending on the extent of your changes, it might be faster to save (:w
) your file with a different name, and then use sudo
and cat
to overwrite the content of the original file:
sudo sh -c 'cat changed > file'
Note that both cp
and mv
will replace the original file and its attributes (ownership, permissions, ACLs) will be lost. Do not use them unless you know how to fix the permissions afterwards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With