A Bash script can read lines from standard input. Or, a Bash script can read input that it prompts the user to enter. But, can a Bash script do both of those?
For example, I want my script to read multiple file paths from standard input, perform some processing on them, then prompt the user to determine whether to continue to the next step. However, the following does not work. The read -p
that I use to prompt the user continues to read from standard input, fetches an empty value, and considers that to be a no response.
A script named test:
#!/bin/bash
while read line; do
echo I read a line: \'$line\'
# Process the line...
done
read -p "Do you want to continue? (y/n) " answer
echo I read answer: \'$answer\'
case ${answer:0:1} in
y|Y ) echo Do the next step...;;
* ) echo Bail;;
esac
echo Done
Execute the script:
[man@machine ~]$ find . -name '*.tif' | test
I read a line: './alpha.tif'
I read a line: './bravo.tif'
I read a line: './delta.tif'
I read answer: ''
Bail
Done
Once the script has exited the while loop, and it gets to the read -p
to prompt the user, can I force it to wait for user input?
Or, am I just "Doing it wrong"? Is it not typical for a Bash script to read from standard input and also prompt for user input?