Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash read inside a loop reading a file

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
like image 359
SoulNothing Avatar asked Mar 11 '12 01:03

SoulNothing


People also ask

How do you iterate through a file in bash?

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).


1 Answers

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> _
like image 55
paxdiablo Avatar answered Sep 23 '22 04:09

paxdiablo