使用使用系统命令的 bash 脚本;当 COMMAND 向您询问某事时,您将如何输入?

With a bash script that utilizes system commands; how would you have it input when the COMMAND asks you for something?

所以假设终端中的正常命令 运行 是这样的....

user$ thecommand
Please enter your first name:
>

然后等待您输入您的名字...简单明了,但如果在 bash 脚本中,我会尝试做类似的事情:

#! /bin/bash
 echo "What is your name?"
     read name
 thecommand

我如何让脚本输入“$name”来响应 "thecommand",而不是让用户自己手动输入?

您可以像这样通过管道添加输入:

echo yourname | ./yourscript

如需更多输入,您可以使用 printf

printf "input1\ninput2" | ./yourscript

其中 \n 表示换行,它将像新输入一样使用。

运行 你的脚本像:

./yourscript.sh < file.txt

其中 file.txt 将包含名称。

现在您的脚本将从文件 (file.txt) 中查找名称,在 file.txt 中您可以键入将作为读取命令输入的名称。 read 命令一次在线读取,所以如果你的脚本中有多个 read 命令,你应该在 [=25= 中有多行] 文件

对于复杂的情况,例如,如果您的输入取决于命令的输出,您可以编写一个 "expect" 脚本。

要查看它是如何工作的,您可以交互式地自动生成这样的脚本

$ autoexpect thecommand

然后运行它

$ expect -f script.exp