Reputation: 147
i want to use read cmd in a while that read line per line from a file, but i have a problem in line 4 in this script :
while read a
do
echo before
read var
echo after
done < file1
the result is :
before
after.
Can you help me to fix this problem????
Upvotes: 1
Views: 1439
Reputation: 77107
A file descriptor can really only point to one file at a time. Every invocation of read
you have there reads from standard input, including the one in the middle. If you want to read
from something else, you have to tell read
to use another file descriptor.
exec 5< file1 # assign file1 to the file descriptor number 5.
# ("open for reading" as it were)
while read <&5 a; do # read from fd5
echo before
read var # read from fd0
echo after
done
exec 5<&- # Reset fd 5 ("close the file" as it were)
You can also use read -u 5
to read from a specific descriptor in bash.
Upvotes: 3