Is Vim safe to use in combination with sudo?

Yes, it is safe.

The problem with sudo gedit is because GUI applications use certain files, such as ~/.cache/dconf, and after elevated gedit that file becomes root-owned. Well, that particular file contains user-specific settings for GUI applications, including desktop, so if the system can't read those settings - it's bad. IIRC a user can't start a particular desktop. The user's recent files data recently-used.xbel also gets affected.

On the other hand, Vim doesn't have that problem. It uses no GUI-related database and doesn't put anything into recently-used.xbel. It was created for a console-only purpose, although gVim also exists. In fact, on some systems Vim is your only choice of editor. So it is safer than gedit by virtue of not causing the same problems. You're still editing as root in both cases, so you could cause problems with improper editing.

According to this blog post:

The first time you use vim, the file ~/.viminfo is created, and if you use sudo vim the first time you use vim after installing it on a fresh system, the permissions on ~/.viminfo will have the owner set to root instead of the default user.

While the author points out it can lead to issues, there's nothing complex - just chown the file back to yourself.

See also:

  • What specific bad things happen when gedit is used with sudo?

It's also possible to use sudoedit to achieve this; it opens a temporary copy of the file in your editor, with your editor running as you. From the man page:

  1. Temporary copies are made of the files to be edited with the owner set to the invoking user.

  2. The editor specified by the policy is run to edit the temporary files. The sudoers policy uses the SUDO_EDITOR, VISUAL and EDITOR environment variables (in that order). If none of SUDO_EDITOR, VISUAL or EDITOR are set, the first program listed in the editor sudoers(5) option is used.

  3. If they have been modified, the temporary files are copied back to their original location and the temporary versions are removed.

This works fine with vim (it's what I generally do) and I imagine it would let you use gedit too. There are some security restrictions.


The link is very old (2013). It recommends using gksudo or gksu for graphical applications but both of those are becoming obsolete. Later on the accepted answer also suggests sudo -H though.

The general consensus in the Ask Ubuntu community recently is to use:

sudo -H gedit /path/to/filename

The only problem remains that sudo doesn't have a profile for tab settings, extensions, word wrap, font name, font size, etc. You can inherit these from your user profile though with a wrapper script like this: How can I sync my root gedit with my user gedit's preferences?

Tags:

Vim

Sudo