Is it possible to save as sudo from nano after you've forgotten to run as sudo?

No, you can't give a running program permissions that it doesn't have when it starts, that would be the security hole known as 'privilege escalation'¹.

Two things you can do:

  1. Save to a temporary file in /tmp or wherever, close the editor, then dump the contents of temp file into the file you were editing. sudo cp $TMPFILE $FILE. Note that it is not recomended to use mv for this because of the change in file ownership and permissions it is likely to cause, you just want to replace the file content not the file placeholder itself.
  2. Background the editor with Ctrl+z, change the file ownership or permissions so you can write to it, then use fg to get back to the editor and save. Don't forget to fix the permissions!

¹ Some editors are actually able to do this by launching a new process with different permissions and passing the data off to that process for saving. See for example this related question for other solutions in advanced editors that allow writing the file buffer to a process pipe. Nano does not have the ability to launch a new process or pass data to other processes, so it's left out of this party.

I just tried nano, and what I found most surprising is it doesn't even warn you that the file is read-only when you start trying to edit the file. (UPDATE: Apparently nano 2.2 does warn; 2.0 doesn't.)

Here's a (basic) script that does that.

It checks if you can edit the file, and if you can't, it runs "nano" as root instead.

/usr/local/bin/edit (or ~/bin/edit)

sudo=                       # empty is false, non-empty is true
editor=nano                 # XXX check $EDITOR and $VISUAL

if test -e "$1" && test ! -w "$1"; then
    if test -t 0 && test -t 2; then
        printf "%s is not writable.  Edit with sudo? [y/n] " "$1" 1>&2
        read -n 1
        case $REPLY in
            printf "\nExpected y or n.  Exiting.\n" 1>&2
            exit 1
        printf "%s is not writable.  Fix the permissions or run \"view\" instead." "$1" 1>&2
        exit 1

${sudo:+sudo} "$editor" "$1"

And a command I called view so that you can avoid the prompt if you know you aren't going to make any changes.

/usr/local/bin/view (or ~/bin/view)


"$editor" $readonlyflag "$1"

There's already a program called view that's part of Vi/Vim, so feel free to suggest a better name.
(But I think a full implementation of this program would make Vi's view redundant.)

Full versions