Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I "read" a variable on a while loop

How can I read from variable with while read line?

For example:

the_list=$(..code..)  while read line do         echo $line  done < $the_list 

using the code above gives me error:

./copy.sh: line 25: $the_list: ambiguous redirect 
like image 413
Crazy_Bash Avatar asked Oct 29 '12 13:10

Crazy_Bash


People also ask

Can you use a variable in a while loop?

Yes. you can declare a variable inside any loop(includes do while loop.

What is IFS in while loop?

The while loop syntax IFS is used to set field separator (default is while space). The -r option to read command disables backslash escaping (e.g., \n, \t). This is failsafe while read loop for reading text files.


2 Answers

You can write:

while IFS= read -r line do     echo "$line" done <<< "$the_list" 

See §3.6.7 "Here Strings" in the Bash Reference Manual.

(I've also taken the liberty of adding some double-quotes, and adding -r and IFS= to read, to avoid too much mucking around with the contents of your variables.)

like image 189
ruakh Avatar answered Nov 28 '22 19:11

ruakh


If you do not use the variable for anything else, you can even do without it:

while read line ; do     echo $line done < <( ... code ... ) 
like image 21
choroba Avatar answered Nov 28 '22 19:11

choroba