在 bash here-document 中模拟 ENTER 键

Simulate ENTER key in bash here-document

有没有办法模拟 bash 脚本中的 ENTER 键,通过此处文档 (EOF) 将值输入代码。在 bash 中很容易实现,参见 question 6264596

伪代码:

 #!/bin/bash
 code_executable << EOF
 value1
 value2 
 EOF

value2后需要跟回车return,即从shell.

执行时回车

谢谢大家。

在终端上模拟可执行文件 运行:

  $./code_executable
  >Do you want to continue? yes or no
  User: y
  >Enter number:
  User: 314 

如果用户在输入 314 后没有按键盘上的 ENTER,则可执行 hangs/halts 并等待。

编辑:查看标准输入缓冲中的异常,这些异常阻止 EOF 将参数传递给可执行文件,如下面的@that other guy answer 所示。

Enter 通常由换行表示,而不是回车 return。程序经常被回车 return 混淆,所以终端会自动将它们翻译成换行符。

您可以在十六进制转储中看到:

holen@vidarh2 11:14 ~ $ hexdump -C
(press enter several times, end with ctrl+d)
00000000  0a 0a 0a 0a                                       |....|
           ^----------- line feeds

如果您查看您的脚本,您会发现它已经在 value2 和尾随 space:

之后添加了一个
$ cat yourscript 
#!/bin/bash
hexdump -C << EOF
value1
value2 
EOF

$ ./yourscript 
00000000  76 61 6c 75 65 31 0a 76  61 6c 75 65 32 20 0a     |value1.value2 .|
                                        line feed ----^

下面是这个工作的一个例子:

$ ./ex1
Continue?
yes
Number?
123
You wrote: 123

$ ./ex1 << EOF
> yes
> 123
> EOF
Continue?
Number?
You wrote: 123

这是一个由于程序中的缓冲错误而失败的示例,即使程序在 运行 交互时看起来完全相同但接收到错误的输入:

$ ./ex2
Continue?
yes
Number?
123
You wrote: 123

$ ./ex2 << EOF
yes
123
EOF

Continue?
Number?
You wrote: yes

这是另一种缓冲错误的第三个示例,其中程序以交互方式工作,但似乎没有收到来自此处文档的输入:

$ ./ex3
Continue?
yes
Number?
123
You wrote: 123

$ ./ex3 << EOF
yes
123
EOF
Continue?
Number?
You wrote: 

他们分别阅读 fscanf(stdin, ..)fdopen(0, "r"); fscanf(file, ...read(0, buffer, 1024) 的行。只有第一个是正确的。

* 请参阅 了解有用的背景信息和实际问题的提示。
* 这个答案假设一个行为良好的程序从 stdin 读取提示输入——事实证明,不使用这样的程序正是 OP 的问题:当提供输入时,他们的程序表现不同通过标准输入而不是通过交互式输入。

让我们用以下脚本模拟您的可执行文件:

#!/usr/bin/env bash

printf ">Do you want to continue? (y)es or (n)o: "
read -r -n 1  confirm  # NOTE: A *single* keypress terminates input here.
printf "\nUser: $confirm\n"

printf ">Enter number: "
read -r  number
printf "User: $number\n"

使用 here-document:

通过 stdin 向此脚本提供问题中的示例输入
./code_executable <<EOF
y314
EOF

请注意 y314 之间没有换行符,以说明第一个提示 需要按 ENTER 键 提交输入 - 只有一个字符。

对于 here-document,整个输入总是以换行结尾 (\n)就好像按下了 Enter (如 中所述),因此将输入提交到第二个提示。

可以在结束 EOF 定界符之前简单地添加额外的提示输入,每个额外的输入都需要 Enter 在其自己的行上提交。

./code_executable <<EOF
y314
next input
...
EOF