Nano: Forgot Sudo and Need to Save A File You Don't Have Permissions to Save

You've opened a file from the root system without using sudo and you're editting it without realizing you don't have write permissions. After all your edits, what do you do? Don't lose your file!--you just need to change the save path! You can do that in Nano's save prompt!

So I'm racing to get a LAMP stack up and going on one of my computers. I need to update the php.ini file which resides in the root file-system at /etc/php/7.4/cli/php.ini. In my haste, I opened up the document from within its file path using $ nano php.ini and started any number of edits. I hit ctl-o to save, and Nano gives me an unsurprising line about how I don't have permissions to save the file. Ever seen something like this?

Nano -- error writing php.ini: Permission denied
When you forget to use sudo to open a file owned by root...

What should you do in this situation? Is it a complete loss? Do you need to exit out and start all your changes again? NO--YOU DO NOT! Don't waste your time. All you need to do is to specify a save path within your user path: i.e., /home/username/Documents/php.ini or, even ~/php.ini

It will be far less work to just save the file in your own user path and then move it back down to the root file system. It's not outwardly obvious from within Nano that you can even do this, but it's actually quite simple. When you hit this problem, try and save your changes once more (with ctl-o); this time, when Nano asks you to give a name to the file, take the current name and just add a path to it that falls within your user path--like so:

adding a path to the file name when saving in Nano
An, "AHA!" kind of moment?!?

That's it. Now, that it's saved, just move the file back into it's original root directory, i.e., $ sudo mv /home/username/Documents/php.ini /etc/php/7.4/cli/php.ini. You may need to restore the owner of the file as well. In my case, since the php.ini is owned by root, I can just run $ sudo chown root: /etc/php/7.4/cli/php.ini

Quick note on the chown syntax above:

You'll often see chown used in the following format chown [user]:[group]; in order to change the ownership of a file to both the user 'root' and the group 'root', you would typically type that out like this: chown root:root. In Bash 4.4.20 you can write this with shorthand (as I've done in the section above): chown root:. This extends the ownership of the file to both the 'root' user and the 'root' group.

There you have it! Easy as pie!