0

I have this settings in SSH configs (/etc/ssh/sshd_config)

AllowUsers root john

I want to add jane to the end of the line

AllowUsers root john jane 

I've tried

sed -i -e '/AllowUsers/{s/:/ /g;s/.*=//;s/$/ jane/p}' /etc/ssh/sshd_config && cat /etc/ssh/sshd_config

I kept getting this result

AllowUsers root john jane 
AllowUsers root john jane 

Why does extra line come?


Note

If I somehow run that command twice

I will get these result

AllowUsers root john jane 
AllowUsers root john jane 
AllowUsers root john jane 
AllowUsers root john jane 

run it again x3 times, will get me this

AllowUsers root john jane 
AllowUsers root john jane 
AllowUsers root john jane 
AllowUsers root john jane 
AllowUsers root john jane 
AllowUsers root john jane 
AllowUsers root john jane 
AllowUsers root john jane 
AllowUsers root john jane 
AllowUsers root john jane 
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
code-8
  • 54,650
  • 106
  • 352
  • 604
  • 1
    (Speaking to original title and tagging:) This is not meaningfully a bash question -- `sed` is not a feature of bash, a part of bash, distributed or versioned with bash, etc; the same behavior would happen if sed were, say, started from Python with `shell=False`, from C via an `execv`-family syscall, etc. – Charles Duffy Aug 26 '20 at 21:30
  • `sed '/^AllowUsers[[:blank:]]/s/$/ jane/' /etc/ssh/sshd_config` – M. Nejat Aydin Aug 27 '20 at 05:12

1 Answers1

5

The p flag in s/$/ jane/p will print the pattern space. Then pattern space will be printed again when the cycle is ended, resulting in two lines. Remove the p flag.

That said, just:

sed 's/AllowUsers .*/& jane/'
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • Tried, and nothing seem added ! Did you test that command ? – code-8 Aug 26 '20 at 21:40
  • `sed 's/AllowUsers .*/& jane/' <<<'AllowUsers root john'` outputs `AllowUsers root john jane` – KamilCuk Aug 26 '20 at 21:41
  • Ok seems working now. What if I want to insert variable ? `sed 's/AllowUsers .*/& ${user}/' /etc/ssh/sshd_config` – code-8 Aug 26 '20 at 21:47
  • 4
    Then you should become acquainted with the [difference between single and double quotes in bash](https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash) – KamilCuk Aug 26 '20 at 21:50
  • 1
    @cyber8200 see also https://stackoverflow.com/questions/7680504/sed-substitution-with-bash-variables for things you need to take care when using shell variables with sed – Sundeep Aug 27 '20 at 05:49