mora mora - 1 year ago 48
Bash Question

Is it possible to use "read" function with standard input explicitly in shell script under while sentence which is working with file input?

I am learning shell script. I have a data file. a row represents data of a account.

a data file: data.dat

name0 domain0 password0
name1 domain1 # this line is lack of third data.

The following script displays all data loading data file by "read" function line by line.

a example script:



while read V1 V2 V3
if [ -z "$V3" ]; then
# when V3 is empty, I want to get it through standard input
# but it load data from $INPUT_FILE
read V3 # Here is my problem.
# read V3 < /dev/stdin # I want like this.
echo "V1 = $V1, V2 = $V2, V3 = $V3"
done < $INPUT_FILE

run script by

sh data.dat

The problem is I could not use read function with standard input inside while sentence because the while sentence uses redirection of data file.
The third column in data file may lack. I would ask user who runs the script to input the lacked data.

Does anyone have solutions or suggestions?
Thank you very much.

Answer Source

You can read my answer here.

You can use exec feature to open the input file using different fd and to read from stdin.

exec 5<${INPUT_FILE}
while read -u 5 V1 V2 V3
 if [ -z "$V3" ]; then
   read V3
 echo "V1 = $V1, V2 = $V2, V3 = $V3"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download