< Return to main page

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

#!bash; 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 $@
        $nano $@

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]?

< Return to main page

You're looking at a very minimalistic archived version of this website. I wish to preserve to content, but I no longer wish to maintain Wordpress, nor handle the abuse that comes with that.