Wintermute
Wintermute

Reputation: 3045

bash variable expansion piped to ssh

I can't get my head around how to declare / refer to these variables in a shell script.

Given the contents of commands_to_execute_on_remote.sh as:

for c in 1 2 3 4 5
do
    supervisorctl restart broadcast-server-${ENVIRONMENT_NAME}-${c}
done

Where ENVIRONMENT_NAME is declared as an environment variable on the local machine...

When I'm running this from a local machine as, e.g.:

cat commands_to_execute_on_remote.sh | ssh [email protected]

How do I refer to those variables in order that, by the time the script is piped to the remote box, $ENVIRONMENT_NAME is populated with the actual value but $c is - obviously - a loop counter within the script?

Upvotes: 2

Views: 319

Answers (1)

tripleee
tripleee

Reputation: 189327

Putting the commands in a separate file is an unnecessary complication.

ssh [email protected] <<____EOF
    for c in 1 2 3 4 5; do
        supervisorctl restart broadcast-server-${ENVIRONMENT_NAME}-\$c
    done
____EOF

Notice how you want $c to be evaluated in the remote ssh shell (so you need to escape it from your local shell) while $ENVIRONMENT_NAME gets expanded by your local shell before the command line is sent to the remote server.

If you insist on putting the script snippet in a file, someething like

sed "s/[$][{]ENVIRONMENT_NAME[}]/$ENVIRONMENT_NAME/" commands_to_execute_on_remote.sh |
ssh [email protected]

allows for that (and avoids the ugly useless cat). (If you remove the technically unnecessary braces, you need to adjust the regex; if ENVIRONMENT_NAME could contain a slash, use a different separator like "s%...%...%".)

Upvotes: 1

Related Questions