Bash read inside a loop reading a file

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-05 03:32:56

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/9651746/bash-read-inside-a-loop-reading-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!