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

后端 未结 3 1147
清歌不尽
清歌不尽 2020-12-10 08:35

I had a bash file which prompted the user for some parameters and used defaults if nothing was given. The script then went on to perform some other commands with the paramet

相关标签:
3条回答
  • 2020-12-10 08:44

    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}"
    }
    
    0 讨论(0)
  • 2020-12-10 08:49

    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.

    0 讨论(0)
  • 2020-12-10 09:06

    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
    
    0 讨论(0)
提交回复
热议问题