gjw80
gjw80

Reputation: 1078

using IFS to delimit by comma, ends after first arg read

I have a var like:

TOPICS=A,B,C,D

And a bash script to read them like:

ssh user@host2 <<EOF
 IFS=$','
 for word in $TOPICS; do
  $PATH_TO_SCRIPT \$word
 done
exit
EOF

But the script at $PATH is only being called for TOPIC 'A' and then the loops exits, any idea what is going on?

Upvotes: 0

Views: 88

Answers (2)

glenn jackman
glenn jackman

Reputation: 247022

Since you have the variable on your local machine (that's what I assume from the question), do the expansion on the local machine:

TOPICS=A,B,C,D
IFS=, read -ra topic_words <<< "$TOPICS"

ssh user@host2 <<EOF
 for word in ${topic_words[*]}; do
  $PATH_TO_SCRIPT \$word
 done
exit
EOF

This will break if there is whitespace in $TOPICS. If that's the case, then:

TOPICS="A a,B b,C c,D d"

ssh user@host2 <<EOF
 IFS=, read -ra topic_words <<< "$TOPICS"
 for word in "\${topic_words[@]}"; do
  $PATH_TO_SCRIPT "\$word"
 done
exit
EOF

I'm assuming your login shell on the remote end is bash.

Upvotes: 0

Barmar
Barmar

Reputation: 781731

ssh user@host2 <<EOF
 IFS=$','
 RTOPICS='$TOPICS'
 for word in \$RTOPICS; do
  $PATH_TO_SCRIPT \$word
 done
exit
EOF

You need to do the variable expansion on the remote system, so that IFS will be used to split the words.

Upvotes: 2

Related Questions