Utilice visudo para esto con un editor personalizado. Esto resuelve todas las condiciones de carrera y los problemas de "pirateo" con la solución de Brian.
#!/bin/sh
if [ -z "$1" ]; then
echo "Starting up visudo with this script as first parameter"
export EDITOR=$0 && sudo -E visudo
else
echo "Changing sudoers"
echo "# Dummy change to sudoers" >> $1
fi
Este script agregará la línea "# Cambio ficticio a sudoers" al final de sudoers. Sin hacks y sin condiciones de carrera.
Versión anotada que explica cómo funciona realmente:
if [ -z "$1" ]; then
# When you run the script, you will run this block since $1 is empty.
echo "Starting up visudo with this script as first parameter"
# We first set this script as the EDITOR and then starts visudo.
# Visudo will now start and use THIS SCRIPT as its editor
export EDITOR=$0 && sudo -E visudo
else
# When visudo starts this script, it will provide the name of the sudoers
# file as the first parameter and $1 will be non-empty. Because of that,
# visudo will run this block.
echo "Changing sudoers"
# We change the sudoers file and then exit
echo "# Dummy change to sudoers" >> $1
fi
echo "$USER ALL=NOPASSWD:/usr/bin/rsync" | (sudo su -c 'EDITOR="tee" visudo -f /etc/sudoers.d/rsync')
.