I am working on a script that pulls data from a csv file, manipulates the data, and then asks the user if the changes are correct. The problem is you can't seem to execute a read command inside a while loop that is reading a file. A test script is included below, note a in file will need to be created granted it isn't really used. This is just an excerpt from a larger script I am working on. I'm recoding it to use arrays which seems to work, but would like to know if there is any way around this? I've been reading through several bash guides, and the man pages for read and haven't found a 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
The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).
You can fiddle with the file handles so that you still have access to the old standard input. For example, this file qq.sh
will read itself and print each line using your read
loop, 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 saving standard input (file handle 0) into file handle 3 with the 3<&0
, then using the read -u <filehandle>
variant to read from file handle 3. A simple transcript:
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> _
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With