Kendi Balazs
Kendi Balazs

Reputation: 63

Modify /etc/sudoers with sed

I'm trying to write a sed program to append Defaults:user !requiretty after the line Defaults requiretty in /etc/sudoers. I tried the following command:

sudo sed -i '/Defaults    requiretty/a Defaults:user !requiretty' /etc/sudoers 

This is working properly, but only if there are 4 spaces between 'Defaults' and 'requiretty'. I want to modify it in order to work with any number of spaces, so I tried the following:

sudo sed -i '/Defaults\s+requiretty/a Defaults:user !requiretty' /etc/sudoers

I checked the pattern on regexr and it was okay, but still the command does not insert the required line. Why not?

Upvotes: 2

Views: 2917

Answers (2)

Alex G
Alex G

Reputation: 211

Working from Mustafa's answer, here's a way to do the same thing with some safety checks added

SUDOER_TMP=$(mktemp)
cat /etc/sudoers > $SUDOER_TMP
sed -i -e 's/PATTERN/OUTPUT/' $SUDOER_TMP
visudo -c -f $SUDOER_TMP && \ # this will fail if the syntax is incorrect
    cat $SUDOER_TMP > /etc/sudoers
rm $SUDOER_TMP

Upvotes: 2

Mustafa DOGRU
Mustafa DOGRU

Reputation: 4112

try this;

sed '/Defaults.\s\s.requiretty/a Defaults:user !requiretty' /etc/sudoers

Upvotes: 3

Related Questions