Change default editor to vim for _ sudo systemctl edit [unit-file] _

editorssystemdvim

[4.13.12-1-ARCH with gnome3 and gdm on Xorg]

I already have set my VISUAL and EDITOR env-vars to vim. Similarly I did try SYSTEMD_EDITOR="vim"; export SYSTEMD_EDITOR in my ~/.bashrc, to no avail.

When modifying unit files in Arch (systemd) via

 $ sudo systemctl edit _unit_ 

I find myself staring at nano. Life is too short and I want vim by all means. How do I do this ?

Best Answer

First method, you can add this line to ~/.bashrc:

export SYSTEMD_EDITOR=vim

And then sudo visudo and add this line:

Defaults  env_keep += "SYSTEMD_EDITOR"

Start new bash session to take effect, then run sudo systemctl edit <foo> as usual.

Second method is use update-alternatives:

Install your desired editor, e.g. vim.gtk3:

$ which editor
editor is /usr/bin/editor
$ sudo update-alternatives --install "$(which editor)" editor "$(which vim.gtk3)" 15

Then choose your desired editor:

$ sudo update-alternatives --config editor
There are 7 choices for the alternative editor (providing /usr/bin/editor).

  Selection    Path                Priority   Status
------------------------------------------------------------
  0            /usr/bin/vim.gtk3    50        auto mode
  1            /bin/ed             -100       manual mode
* 2            /bin/nano            40        manual mode
  3            /usr/bin/code        0         manual mode
  4            /usr/bin/gedit       5         manual mode
  5            /usr/bin/vim.basic   30        manual mode
  6            /usr/bin/vim.gtk3    50        manual mode
  7            /usr/bin/vim.tiny    15        manual mode

Press <enter> to keep the current choice[*], or type selection number: 6
update-alternatives: using /usr/bin/vim.gtk3 to provide /usr/bin/editor (editor) in manual mode

Third method is direct set the EDITOR on runtime:

sudo EDITOR=vim systemctl edit <foo>

The precedence are first method > third method > second method.

Don't try to set "GUI" editor such as gedit because Why don't gksu/gksudo or launching a graphical application with sudo work with Wayland? and Gedit uses 100% of the CPU while editing files

Related Question