I'm working on a bash script that parses a tab separated file. If the file contains the word "prompt" the script should ask the user to enter a value.
It appears that while reading the file, the "read" command is not able to read from standard input as the "read" is simply skipped.
Does anybody have a work around for doing both reading from a file as well as from stdin?
Note: The script should run on both Git Bash and MacOS.
Below is a little code example that fails:
#!/bin/bash
#for debugging
set "-x"
while IFS=$'\r' read -r line || [[ -n "$line" ]]; do
[[ -z $line ]] && continue
IFS=$'\t' read -a fields <<<"$line"
command=${fields[0]}
echo "PROCESSING "$command
if [[ "prompt" = $command ]]; then
read -p 'Please enter a value: ' aValue
echo
else
echo "Doing something else for "$command
fi
done < "$1"
Output:
$ ./promptTest.sh promptTest.tsv
+ IFS=$'\r'
+ read -r line
+ [[ -z something else ]]
+ IFS=' '
+ read -a fields
+ command=something
+ echo 'PROCESSING something'
PROCESSING something
+ [[ prompt = something ]]
+ echo 'Doing something else for something'
Doing something else for something
+ IFS=$'\r'
+ read -r line
+ [[ -z prompt ]]
+ IFS=' '
+ read -a fields
+ command=prompt
+ echo 'PROCESSING prompt'
PROCESSING prompt
+ [[ prompt = prompt ]]
+ read -p 'Please enter a value: ' aValue
+ echo
+ IFS=$'\r'
+ read -r line
+ [[ -n '' ]]
Sample tsv file:
$ cat promptTest.tsv
something else
prompt
otherthing nelse
readis reading from standard input -- you've redirected the first parameter to the script ($1) as standard input, so it isn't the keyboard any more. You can't usereadto read from both the file and from the keyboard at the same time.