Edit sudoers file from a script
brian_s 270002K5X3 Visits (17871)
If you need to edit the sudoers file from a script, you might be tempted to directly edit the file. But like it says at the top of /etc/sudoers - the file must only be edited with the visudo command. This is because visudo validates the syntax before putting the new file in place. Without this syntax validation it is very easy to make a mistake in the file after which sudo no longer works (hopefully at that point you have the root password so you can still access root without sudo :) )
Here is an example of how a line can be added to the /etc/sudoers file from a script while still using the visudo command to ensure the syntax is valid:
The way the script works is when it is run it detects it was run with no parameters, and therefor goes to the "else" part of the code. It sets the EDITOR variable to the name of the script itself ($0), and then calls visudo. visudo runs the "EDITOR" program (in our case this script) with the temporary sudoers file name as a parameter. When the script is run by visudo, it has a parameter so it runs the first section of the "if" statement which echo's a line in to "$1" which is the name of the temporary sudoers file that visudo passed. The script then ends, and visudo validates the syntax and puts the sudoers file in place if no errors were found.
The previous example shows how to add a line, if you want to modify or delete lines you could use the ed editor (for more details on editing files with ed from a script see Script file edits with the "ed" editor. )
Here is an example to change a line in /etc/sudores. In this example, the "root ALL=(ALL) ALL" line is commented out:
Here is an example of deleting a line in /etc/sudoers. In this example, the "root ALL=(ALL) ALL" line is deleted: