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


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.

  • This question and answer were spun off with only minor edits from a section in the canonical "how to become root" question. All credit goes to the creators of that original answer. – tshepang Dec 9 '13 at 21:53
  • @Tshepang what just happened? – strugee Dec 10 '13 at 1:07
  • 2
    Meta info like belongs to the Comments section. – tshepang Dec 10 '13 at 7:12
  • 1
    And you should not edit the crontab files directly but use crontab -e (as this also may do syntax checking). – Reinstate Monica - M. Schröder Dec 10 '13 at 22:14

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.

|improve this answer|||||
  • 1
    That's why we have programs like rcs and etckeeper. – Reinstate Monica - M. 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 4:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.