How do I edit a file as root?

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x