1

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????

2
  • 1
    Please show us the actual error. Commented Mar 25, 2014 at 23:57
  • Where do you want the read inside the loop to read from? The termimnal (even if I/O is redirected from a pipe or file)? From the standard input of the main script? @kojiro has given you a decent answer. Commented Mar 26, 2014 at 0:10

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

You might consider documenting the read <&5 alternative for folks not using bash.
Should you add exec 5<&- after the loop for symmetry and to clean up? Clearly, if the script is about to exit, it is far from critical, but closing that which you open is generally a good idea and avoids resource leaking/exhaustion.
I'd consider scoping the redirection to the loop, rather than starting it prior and needing to clean up after. (while ... done 5< file1)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.