user1777907
user1777907

Reputation: 1375

Running multiple commands through ssh

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.

Upvotes: 1

Views: 1999

Answers (1)

Joao Morais
Joao Morais

Reputation: 1925

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.

Upvotes: 3

Related Questions