0

How would you suggest to consecutively assign one variable per word of string?

I am looking for the short command: one-liner and without loop if possible. It should have of the form

echo "<sring>"  | your_command

Example:

  • The string is "word1 word2 word3"
  • I want to assign the variable w1 to word1, w2 to word2 and w3 to word3.
2
  • after storing into variable, what kind of operation you are going to do with that ? so.. we can advise more flexible solution
    – Kamaraj
    Feb 10, 2017 at 9:50
  • Variables would be assigned and used in a script. Feb 10, 2017 at 10:11

1 Answer 1

3

This works in ksh93 but not in bash since bash runs the read in a sub-shell:

echo "word1 word2 word3" | read w1 w2 w3
printf '"%s"\n' "$w1" "$w2" "$w3"

This means that you simply can't have an assignment as part of a pipeline in bash.

The workaround is to use the variables before the pipeline sub-shell exits:

echo "word1 word2 word3" | { read w1 w2 w3 && printf '"%s"\n' "$w1" "$w2" "$w3"; }

or,

echo "word1 word2 word3" | {
  read w1 w2 w3
  printf '"%s"\n' "$w1" "$w2" "$w3"
}

This works in both shells:

read w1 w2 w3 <<<"word1 word2 word3"
printf '"%s"\n' "$w1" "$w2" "$w3"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .