15

Are there any special considerations to editing a file as root? What is the safest way to do this?

strugee
  • 14,951

2 Answers2

17

Obviously, if you know how to run any command as root, you can run an editor. But that's not the most convenient or the safest method.

sudoedit (or its synonym sudo -e) is a mode of sudo where you edit a temporary copy of a file in your favorite editor, and that copy is moved into place when you finish editing.

sudoedit /etc/fstab

Note: There are a few files that you should not edit directly.

Never edit /etc/sudoers directly. Always use the visudo command for that. If you make a mistake in the syntax of the sudoers file, you could be locked out of the root account! When you run visudo, it lets you edit a temporary copy of the file and performs a syntax verification before replacing the actual file by your edits.

The same principle applies to the user, group, user password, and group password databases, /etc/passwd, /etc/group, /etc/shadow, and /etc/gshadow, respectively. On systems where they are available, use the vipw, vigr commands for /etc/passwd and /etc/group. To edit the password databases, pass the -s option. For example, to edit /etc/gshadow, use vigr -s.

strugee
  • 14,951
0

Always make sure to keep a backup of the file you are editing. Some people like to put a time stamp on after that. This ensures you can always revert (well, hopefully )if the system breaks as a result of the change. In addition to the command listed by strugee, most set ups will allow you to run your usual editors (vi,vim,nano,emacs). Just be cognicent whether the file is read only or not.

Luke
  • 87
  • 1
    That's why we have programs like rcs and etckeeper. – Martin Schröder Dec 10 '13 at 22:15
  • "most setups will allow you to run your usual editors" - yes, of course. but note the second sentence in my answer - directly running an editor isn't the safest way to do it. there's virtually no downside to sudoedit. – strugee Dec 11 '13 at 04:18