Automate sudo nano; something I should’ve done a loooong time ago

Remember those countless times you’ve edited a file with nano, didn’t notice that you weren’t root at the time, and carefully made your configuration changes and saved the file, only to find out that you weren’t root and you have no rights to modify the file?

I do. And it sucks. Big time. And if bash wasn’t so awesome in helping you tune your shell into what you want for yourself, I probably would’ve found some configuration in nano to warn me properly. But, bash is awesome, and after all I like tuning my stuff into my stuff. So here’s my solution:

Edit ~/.bashrc and add the following lines

(GIST: 1087457)
function nano() { 
    nano=`which nano`; 
    if ([ -e "$1" ] && ! [ -w "$1" ]) || ( ! [ -e "$1" ] && ! [ -w "`dirname $1`" ]); then 
        read -n 1 -p "$1 is not editable by you. sudo [y/N]? " y
        [ "$y" == "y" ] || [ "$y" == "Y" ] && echo -e "\n" && sudo $nano $@
    else 
        $nano $@
    fi
}

source your file, or log out and log back in again.

$ . ~/.bashrc

And you’re done! You’ll get a nice prompt asking you if you want to sudo to change the file if you do not have privileges to edit the file. Check, done, and done. Gotta love that unix environment.

$ nano /etc/apt/sources.list
/etc/apt/sources.list is not editable by you. sudo [y/N]?

5 Comments

  • Nice! Briljant in it’s simplicity. Have run into this on numerous occasions but it was too small an annoyance to actually do something about it ๐Ÿ™‚

    Ran into this problem when editing my bash.bashrc, the irony ๐Ÿ™‚ Thanks for this useful snippet.

  • Awesome thanks for this snippet! You can btw (assuming you are in your home folder) also just do this to reload your bashrc:

    . .bashrc

    Like it a bit better then to logout / login !

    Thanks again…

  • True, that’s what “sourcing” is, you’ll execute the script in the current scope, which means the variables and functions defined in that script (in this case your .bashrc) will remain in the scope of your session. The ‘dot’ operator (as mentioned in the post) is a shortcut for the ‘source’ command ๐Ÿ™‚

  • Haha, this problem sounds very familiar ๐Ÿ™‚

    Tried the above function, works great except for the fact that your job history ends up looking like:

    [3]- Stopped $vi $@ [4]+ Stopped sudo $vi $@

    Any ideas as to how to solve that?

  • No idea, sorry ๐Ÿ™‚ But if you find the solution anyway, please report back!

Leave a Reply to Rik Cancel reply

Your email is never shared.Required fields are marked *