Linux – Set default editor for crontab -e invoked with sudo

crontablinuxsudotext-editorsvim

I'm using Bash on Debian Squeeze. I just read this topic: change default text editor for crontab to vim

I have exported both variables VISUAL and EDITOR to vim for normal user and for root. And this works – when I type crontab -e as normal user or root, crontab runs vim for editing.

But running sudo crontab -e opens nano.

Running sudo echo $EDITOR (or $VISUAL) gave vim int output.

Best Answer

By default and for security purposes, sudo does not preserve the user environment.

There are multiple ways to deal with this; for your specific case, I recommend adding VISUAL=/usr/bin/vim (and EDITOR=/usr/bin/vim for programs that use the wrong one) to /etc/environment.

Second choice, if you have a permissive sudo configuration (perhaps because it's just you, or all sudoers have real root access anyway) is to run visudo and add Defaults env_keep="VISUAL EDITOR" to allow all sudoers to specify their own (i.e. preserve that environment variable).

Your existing sudoers file may well already have (or include) one or more env_keep statement(s), e.g. this (from the pastebin example):

Defaults    env_reset
Defaults    env_keep =  "COLORS DISPLAY HOSTNAME HISTSIZE INPUTRC KDEDIR LS_COLORS"
Defaults    env_keep += "MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE"
Defaults    env_keep += "LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES"
Defaults    env_keep += "LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE"
Defaults    env_keep += "LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY"

The first of those env_keep lines will overwrite whatever edits you make above it (assignment), the other lines extend the list (+=). To keep everything working the way you're used to and unless you have a reason to change the set, I recommend adding a line immediately after those:

Defaults    env_keep += "VISUAL EDITOR"

(There are other options to use your preferred editor, but they're either needlessly complicated or overly permissive and dangerous, so you'll have to read man sudoers, figure them out yourself, and understand what the associated problems might be.)

Related Question