kensuke1984 kensuke1984 - 4 months ago 12
Bash Question

How to create a shell script (/bin/sh) with option -s and read input inside

I want to run a shell script (POSIX) like this.

#!/bin/sh
# this is a.sh
echo your age?
read age
echo "You are $age."


If this is thrown to /bin/sh through standard input as

cat a.sh | /bin/sh -s


then the question is skipped.

How can I ask the question?

Answer

The problem is that /bin/sh is reading the script, and your script is reading input, from the same input file: the pipe fed by cat a.sh.

One solution is to modify your script to read directly from the terminal, not standard input, although that may not be exactly what you want.

echo "your age?"
read age < /dev/tty
echo "Your age $age"

The better solution is to not read the script from standard input; just pass it as an argument to /bin/sh.

/bin/sh a.sh