One possibility would be to pipe the output of your sed command (without the -i
flag) into this script to overwrite the sudoers file if it is safe to do so, without having to try to run the editor non-interactively.
#!/bin/sh
#
# Replaces /etc/sudoers with a new version supplied
# on standard input, but first performs safety checks
# including with "visudo -c"
#
sudoers=/etc/sudoers
tmp_sudoers=$sudoers.tmp # same tmp file as used by visudo
if [ -e $tmp_sudoers ]
then
echo "someone is editing sudoers"
exit 1
fi
# make new version from data on stdin, preserving permissions
# by creating a copy and then overwriting it
cp $sudoers $tmp_sudoers
cat > $tmp_sudoers
# install the new version if it passes checks
succeeded=0
if [ ! -s $tmp_sudoers ]
then
echo "replacement file is empty"
elif diff -q $sudoers $tmp_sudoers > /dev/null
then
echo "there were no changes"
elif ! visudo -q -c -f $tmp_sudoers
then
echo "replacement file is invalid"
else
mv $tmp_sudoers $sudoers
succeeded=1
fi
if [ $succeeded -eq 0 ]
then
rm $tmp_sudoers
exit 1
fi