1

I am trying to run multiple commands using SSH but I am not getting my syntax right. Could someone please give me some help?

ssh "$USER"@"$IP" " \
    CURRENT_HOSTNAME=$(hostname); \
    sed -c -i 's/\($TARGET_KEY *= *\).*/\1$REPLACEMENT_VALUE/' $DISTRO_FILE; \
    sed -c -i 's/$CURRENT_HOSTNAME/$REPLACEMENT_VALUE/' $CONFIG_FILE; \
    hostname $REPLACEMENT_VALUE"

Those commands work fine if they are run locally, but I am getting the following error with when trying to run them through SSH:

sed: -e expression #1, char 0: no previous regular expression

It seems the error comes from

sed -c -i 's/$CURRENT_HOSTNAME/$REPLACEMENT_VALUE/' $CONFIG_FILE; \

as it is trying to read $CURRENT_HOSTNAME which is set before in the SSH itself. I am not sure how to read that variable back. Any clue please?

EDITED the code:

ssh "$USER"@"$IP" "CURRENT_HOSTNAME=\$(hostname);
    sed -c -i \"s/\($TARGET_KEY *= *\).*/\1$REPLACEMENT_VALUE/\" $DISTRO_FILE;
    sed -c -i \"s/\$CURRENT_HOSTNAME/$REPLACEMENT_VALUE/\" $CONFIG_FILE;
    hostname $REPLACEMENT_VALUE"

This works! Thanks a lot!

Thanks.

user1777907
  • 1,235
  • 4
  • 12
  • 27
  • Possible duplicate of [What is the cleanest way to ssh and run multiple commands in Bash?](https://stackoverflow.com/q/4412238/608639) – jww Aug 23 '19 at 20:42

1 Answers1

3

All variables with double quotes will be evaluated by Bash before sending the parameter to the remote machine.

If you want to preserve the $variable you will need to use single quotes instead (escaping single quotes within your commands), or escape all dollar signs you want evaluated on the server side.

You also don't need to escape line break and use semicolon. All line breaks will be included in the parameter.

Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
Joao Morais
  • 1,837
  • 11
  • 20
  • Thanks Jonathan, I've made progress. I understand the idea now. I have an issue right now though because I have local variable (in the local bash script), one remote variable (the CURRENT_HOSTNAME) and sed complains for double quotes. I am updating the code above. – user1777907 Apr 05 '13 at 18:14
  • I got the code to work (solution up there in the edit). Thanks a lot Jonathan! – user1777907 Apr 05 '13 at 18:44