0

I have following line in my script, ${snap[@]} array contain my ssh server list.

      while IFS= read -r con; do
    ssh foo@"$con" /bin/bash <<- EOF
      echo "Current server is $con"
EOF
      done <<< "${snap[@]}"

I want to print current iteration value of the array as the ssh ran successfully, the $con should print current ssh server --> example@server. How would I do that ?

2 Answers 2

2

If the elements in snap are the hosts that you want to connect to, just use a for loop:

for con in "${snap[@]}"; do
  # connect to "$con"
done

"${snap[@]}" expands to the safely-quoted list of elements in the array snap, suitable for use with for.

If you really want to use while, then you can do something like this:

i=0
while [ $i -lt ${#snap[@]} ]; do # while i is less than the length of the array
  # connect to "${snap[i]}"
  i=$(( i + 1 ))                 # increment i
done

But as you can see, it's more awkward than the for-based approach.

Sign up to request clarification or add additional context in comments.

5 Comments

I know for loops can do this, but I'm looking a while solution, thanks.
I would strongly recommend the approach using for, but I have added an option using while anyway.
Why would you use a while loop when the for loop is clearly called for?
You don't need to use set; you can just use a while loop to produce increasing values of i that can be used to index snap.
@chepner yeah you're right, I replaced my example with that simpler option, thanks.
1

Like this :

while IFS= read -r con; do
    ssh "foo@$con" /bin/bash <<EOF
        echo "Current server is $con"
EOF
done < <(printf '%s\n' "${snap[@]}")
#    ____
#      ^
#      |
# bash process substitution < <( )

Or simply :

for server in "${snap[@]}"; do
    ssh "foo@$con" /bin/bash <<EOF
        echo "Current server is $con"
EOF
done

2 Comments

It seems overcomplicated to use a combination of printf and a while read loop to iterate over the contents of an array.
@TomFenech yes, added for loop version

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.