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
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
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.)
If you do not use the variable for anything else, you can even do without it:
while read line ; do
echo $line
done < <( ... code ... )
You can just use
your_code | while read line;
do
echo $line
done
if you don't mind the while loop executing in a subshell (any variables you modify won't be visible in the parent after the done
).
Script file should be in Linux mode. Previously it was in dos mode. I changed it by using dos2unix filename
.
e.g.:
dos2unix sshcopy.sh
Now it works for me.