0

I'm trying to send a sed command using ssh.

Here is my script:

#!/bin/bash

IP_PUBLIC="192.168.0.1"
from="DB_HOST='my_host'"
to="DB_HOST='192.168.0.2'"
    
ssh -oStrictHostKeyChecking=no root@"$IP_PUBLIC" '
    sed -i "s/'"$from'"/'"$to'"/g" /path/to/file;
'

Which throw me the following error:

test: line 9: unexpected EOF while looking for matching `''
test: line 10: syntax error: unexpected end of file

I also tried

#!/bin/bash

IP_PUBLIC="192.168.0.1"

ssh -oStrictHostKeyChecking=no root@"$IP_PUBLIC" '
    sed -i "s/DB_HOST=\'my_host\'/DB_HOST=\'192.168.0.2\'/g" /path/to/file;
'

I got the same error

Content of the file

#!/bin/bash
DB_HOST='my_host'

Need to be

#!/bin/bash
DB_HOST='192.168.0.2'
executable
  • 3,365
  • 6
  • 24
  • 52

2 Answers2

1

Instead of thinking how to double escape stuff, use stdin and pass the actual variables with bash declare -p and functions with declare -f.

IP_PUBLIC="192.168.0.1"
from="DB_HOST='my_host'"
to="DB_HOST='192.168.0.2'"
work() {
    sed -i "s/$from/$to/g" /path/to/file;
}
    
ssh -oStrictHostKeyChecking=no root@"$IP_PUBLIC" bash -s <<EOF
$(declare -p from to)  # hand-pick transfer variable values
$(declare -f work)     # hand-pick transfer code
# everything is properly quoted, as it would be on localhost
work                   # execute the function.
EOF
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • Thanks for the answer but I can't use `bash -s` because I have other commands in there like `systemctl start snmpd;` – executable Mar 12 '21 at 13:25
  • sooooo just `work() { sed -i "s/$from/$to/g" /path/to/file; other command like; systemctl start snmpd; }`. Put them in the function. Or just put them before `EOF` - I do not follow how does that affect not using `bash -s`. – KamilCuk Mar 12 '21 at 13:29
1

Since the variable $from and $to are part of a single quote string(') bash won't expand them to the values.

When to wrap quotes around a shell variable?

Please try the following:

#!/bin/bash

IP_PUBLIC="192.168.0.1"
from="DB_HOST='my_host'"
to="DB_HOST='192.168.0.2'"

ssh -oStrictHostKeyChecking=no root@"$IP_PUBLIC" "sed -i \"s/${from}/${to}/g\" /path/to/file;"
0stone0
  • 34,288
  • 4
  • 39
  • 64