Bash read inside a loop, reading a file

I am working on a script that fetches data from a csv file, manipulates the data, and then asks the user if the changes are correct. The problem is that you cannot execute the read command inside the while loop that reads the file. Below is the test script, note that the file in the file must be created if not used. This is just an excerpt from a larger script I'm working on. I'm rewriting it to use arrays, which seems to work, but would like to know if there is something like that? I've read several bash manuals and man pages to read and haven't found an answer. Thanks in advance.

#!/bin/bash
#########
file="./in.csv"
OLDIFS=$IFS
IFS=","
#########

while read custdir custuser
do
    echo "Reading within the loop"
    read what
    echo $what
done < $file

IFS=$OLDIFS

      

+3


source to share


1 answer


You can play with file descriptors so that you still have access to the old stdin. For example, this file qq.sh

will read by itself and print each line using a loop read

, and also ask you a question after each line:

while read line
do
    echo "    Reading within the loop: [$line]"
    echo -n "    What do you want to say? "
    read -u 3 something
    echo "    You input: [$something]"
done 3<&0 <qq.sh

      



It does this by first storing standard input (file descriptor 0) into file descriptor 3 with 3<&0

, and then using the option read -u <filehandle>

to read from file descriptor 3. Simple transcription:

pax> ./qq.sh
    Reading within the loop: [while read line]
    What do you want to say? a
    You input: [a]
    Reading within the loop: [do]
    What do you want to say? b
    You input: [b]
    Reading within the loop: [echo "Reading within the loop: [$line]"]
    What do you want to say? c
    You input: [c]
    Reading within the loop: [echo -n "What do you want to say? "]
    What do you want to say? d
    You input: [d]
    Reading within the loop: [read -u 3 something]
    What do you want to say? e
    You input: [e]
    Reading within the loop: [echo "You input: [$something]"]
    What do you want to say? f
    You input: [f]
    Reading within the loop: [done 3<&0 <qq.sh]
    What do you want to say? g
    You input: [g]
    Reading within the loop: []
    What do you want to say? h
    You input: [h]
pax> _

      

+7


source







All Articles