How to read from user within while-loop read line?

对着背影说爱祢 提交于 2019-11-30 14:50:38

You pipe data into your the while loops STDIN. So the read in get_ans is also taking data from that STDIN stream.

You can pipe data into while on a different file descriptor to avoid the issue and stop bothering with temp files:

while read -u 9 line; do
   NAME=$(get_ans Name "$line")
done 9< list.txt

get_ans() {
    local PROMPT=$1 DEFAULT=$2 ans
    read -p "$PROMPT [$DEFAULT]: " ans
    echo "${ans:-$DEFAULT}"
}

To read directly from the terminal, not from stdin (assuming you're on a *NIX machine, not a Windows machine):

while read foo</some/file; do
    read bar</dev/tty
    echo "got <$bar>"
done

When you pipe one command into another on the command line, like:

$ foo | bar

The shell is going to set it up so that bar's standard input comes from foo's standard output. Anything that foo sends to stdout will go directly to bar's stdin.

In your case, this means that the only thing that your script can read from is the standard output of the cat command, which will contain the contents of your file.

Instead of using a pipe on the command line, make the filename be the first parameter of your script. Then open and read from the file inside your code and read from the user as normal.

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