2

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?

Mike Finch
  • 746
  • 1
  • 7
  • 20
  • 1
    Based on the other post provided by @thatotherguy, using `/dev/tty` in the following line in my script forces it to correctly wait for user input: `read -p "Do you want to continue? (y/n) " answer < /dev/tty` – Mike Finch Jul 03 '18 at 21:18
  • Don't try to parse the output of `find` like that. Pathnames _can_ contain newlines and backslashes, and `read` can't be used to safely read them. Instead, get `.tif` as a command line argument and let your script execute `find` and do the necessary processing. – Kusalananda Jul 04 '18 at 07:13

0 Answers0