Monday 15 February 2010

bash while loop that reads from a file and asks for user input -



bash while loop that reads from a file and asks for user input -

this question has reply here:

read stdin user input when file redirected stdin 1 reply

i need read lines file. send file in via stdin, if need user input, can't!

here's (contrived) example:

#!/usr/bin/env bash cat <<here >/tmp/mytemp.txt 4 of clubs 2 of hearts queen of spades here while read line ; echo "card: $line" read -p 'is card? ' reply echo "your answer: $answer" echo done </tmp/mytemp.txt

this doesn't work. instead this:

$ ~/bin/sample_script.sh line: 4 of clubs answer: 2 of hearts line: queen of spades answer: $

how can both in same loop?

use 2 different file descriptors.

while ifs= read -r -u 3 from_file; read -r from_user # ...your logic here... done 3< filename

or, not depend on bash extensions:

while ifs= read -r from_file <&3; read -r from_user done 3< filename

(the explicit -r , clearing of ifs necessary read contents without trimming trailing whitespace, expanding backslash escapes, etc; utilize habit in default unless explicitly know want these behaviors).

bash

No comments:

Post a Comment