1

I'm running running ssh commands from client machine on a remote machine:

ssh  -o "StrictHostKeyChecking no" -i $key 'user'@$public_ip "    
i=1;
workerips: "ip1 ip2";
for ip in $worker_ips; do
    echo \"ipis: ${ip} and i is ${i}\"
done;"

My problem is that '$ip' and '$i' are empty inside the 'for' loop. '$i' keeps its value outside the for loop. What am I doing wrong?

2
  • 1
    should the 3rd line not read workips="ip1 ip2";? Actually, you probably need to escape those quotes: workerips=\"ip1 ip2\";. You probably also need to escape each $ to \$ so that it's interpreted on the remote machine rather than locally. Commented Jul 3, 2019 at 22:27
  • thanks escaping $ to \$ fixed it. I already had the 3rd line with escape quotes in code, didn't include that in the question. Commented Jul 3, 2019 at 22:34

2 Answers 2

3

It's a lot easier to do this sort of thing with a heredoc:

$ ssh -o "StrictHostKeyChecking no" -i "$key" user@$public_ip << \EOF
> i=1
> workerips="ip1 ip2"
> for ip in $workerips; do echo "ipis: ${ip} and i is ${i}"
> done
> EOF
Sign up to request clarification or add additional context in comments.

3 Comments

thanks, but I want to run it in an automated script and not an interactive session.
You can use heredocs just fine in a script. The fact that I've displayed an interactive session doesn't change anything. Just remove the first two columns of prompt.
Do you know why the 'for' loop is not working inside the heredoc: << \EOF i=1 for ip in $worker_ips; do echo "ip is ${ip} and i is ${i}" $ip >> ~/uniquefile $i >> ~/uniquefile i=$((i+1)) done EOF commands outside the for loop are working.
1

Depending on what you are trying to do, parallel ssh program (pssh) could work for you.

https://linux.die.net/man/1/pssh

The idea is you can execute the same command across the nodes you define (either across the board or in batches). Basic workloads might be updating a config file across several nodes, more complex cases include things like snapshots across a Cassandra cluster to make sure you have these run at nearly the same time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.