Linux shell su -c 'sed' command

Pure Color :
$ sudo su - root -c 'sed -i '$a\PermitRootLogin yes' etc/ssh/sshd_config'

after run the command,it always displays

sed: -e expression #1, char 2: extra characters after command

and

$ sudo su - root -c "sed -i '$a\PermitRootLogin yes' etc/ssh/sshd_config"

will display

sed: -e expression #1, char 20: unterminated address regex

how should I modify it?

John Kugelman :

Single quotes don't nest. Since you have single quotes in the sed command, use double quotes for the outer set. Then make sure to escape \$a so it's not interpreted as a shell variable named $a.

sudo su - root -c "sed -i '\$a\\PermitRootLogin yes' /etc/ssh/sshd_config"

You can avoid the quoting problems by getting rid of the whole su - business, though. sudo already gives you root access, no need to combine it with su. Once you do that you no longer need two sets of quotes and the problem disappears entirely.

sudo sed -i '$a\PermitRootLogin yes' /etc/ssh/sshd_config

By the way, sed is a bit heavy handed if all you want to do is append a line of text. It will copy the original file to a temporary file, add the line to the copy, and then replace the original with the copy. You can avoid this overhead by using >> or tee -a, either of which will append the line in place without all the copying.

sudo sh -c 'echo "PermitRootLogin yes" >> /etc/ssh/sshd_config'
sudo tee -a /etc/ssh/sshd_config <<< 'PermitRootLogin yes' > /dev/null

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=6510&siteId=1