2

The script is to read a file that contains multiple lines, each line containing a tab-delimited array. I want to execute some remote commands that take those array elements as arguments, with sudo permission. Here is the example script:

while IFS=$'\t' read -r -a line
do
  echo ${line[0]}
  ssh -tty -o StrictHostKeyChecking=no ${line[0]} 'sudo echo ${line[1]}; sudo echo ${line[2]}' 
done < nodes.txt

Here is the example input file:

rivervm-1       dc2     rack1
rivervm-2       dc2     rack2
rivervm-3       dc2     rack3
rivervm-4       dc2     rack4

The output should be 12 variables, each in a new line. However, this is what I got:

rivervm-1
rivervm-2   dc2 rack2
rivervm-3   dc2 rack3
rivervm-4   dc2 rack4

Connection to rivervm-1 closed.

Any idea?

  • The shell won't expand variables within single quotes. – Kusalananda Jan 5 '17 at 19:59
  • @Kusalananda Thanks! I've updated the answer below. – roymaztang Jan 5 '17 at 20:14
0

Firstly, your ssh command is eating your input (coming from nodes.txt), append < /dev/null to it. Appending a & has the same effect since, by putting ssh into background, it detaches it from standard input.

Secondly, as noticed by Kusalananda, your variable ${line[1]} and ${line[2]} are not substituted because they are inside single quotes.

0

Regarding the comment of @Kusalananda, shell won't expand variables within single quotes. That explains why echo inside ssh does not work. After I replace single quotes with double quotes, the output is like:

rivervm-1
rivervm-2   dc2 rack2
rivervm-3   dc2 rack3
rivervm-4   dc2 rack4
dc2
rack1
Connection to rivervm-1 closed.

Still, it only executes the commands on rivervm-1, but not the rest.

I've found a solution to this: adding '&' to the end of ssh command. Could anyone explain to me why this works? Thanks!

  • I have just added an explanation to my answer. – xhienne Jan 5 '17 at 20:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.