如何使用选项 -s 创建 shell 脚本 (/bin/sh) 并读取其中的输入

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

我想 运行 像这样的 shell 脚本 (POSIX)。

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

如果这是通过标准输入作为

抛给/bin/sh
cat a.sh | /bin/sh -s

则此题略过

如何提问?

试试 -n 选项

echo -n "your age?"
read age
echo "Your age $age"

问题是 /bin/sh 正在读取脚本,而您的脚本正在从同一个输入文件读取输入:由 cat a.sh 提供的管道。

一个解决方案是修改您的脚本以直接从终端读取,而不是标准输入,尽管这可能不是您想要的。

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

更好的解决办法是不从标准输入读取脚本;只需将其作为参数传递给 /bin/sh.

/bin/sh a.sh