bash - 如何多次 'expect' 某事?

标签 bash expect

我使用以下脚本通过 expect 处理多个用户输入:

#!/usr/bin/bash

TEST1="Test text"
TEST2="Hello World"

expect -c '
    spawn /home/alexander/read.sh
    expect -re "Please enter some input:.*"
    send "'"$TEST1"'\r\n"
    expect -re "Please enter other input:.*"
    send "'"$TEST2"'\r\n"
    '

这是一个不同的版本:

#!/usr/bin/bash

TEST1="Test text"
TEST2="Hello World"

expect -c '
    spawn /home/alexander/tasks/update/test/Expect/read.sh
    expect {
       "Please enter some input:" { send "'"$TEST1"'\r"  }
       exp_continue
    }
    expect {
        "Please enter other input:" { send "'"$TEST2"'\r" }
    }
    '

read.sh 脚本如下所示:

#!/bin/bash

read -p "Please enter some input: " input_variable
echo "You entered: $input_variable"
read -p "Please enter other input: " other_variable
echo "You entered: $other_variable"

当我单独执行read.sh时,系统会要求我输入两次,该输入也会打印到标准输出。另一方面,expect 脚本似乎不处理第二个输入。我得到的输出如下:

spawn /home/alexander/read.sh
Please enter some input: Test text

You entered: Test text
Please enter other input: 

我做错了什么,如何解决这个问题?

备注:

  • 该脚本必须是带有 bash-shebang 的 bash 脚本。
  • 在第一个脚本中添加 exp_continue 会导致命令返回错误代码:-101 错误。

最佳答案

这有效:

#!/bin/bash

TEST1="Test text"
TEST2="Hello World"

expect -c '
    spawn /tmp/read.sh
    expect {
       "Please enter some input:" { send "'"$TEST1"'\r"
                                   exp_continue
                                  }
        "Please enter other input:" { send "'"$TEST2"'\r"
                                      exp_continue
                                    }
    }'

关于bash - 如何多次 'expect' 某事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20140848/

相关文章:

python - 在 Bash 脚本中获取/激活 Python VirtualEnv

linux - 在文件中找到的每行的增量(第 1 个)数为 1

bash - 在 heredoc 中使用 expect 命令

shell - 带着expect运行命令

scripting - 自动化 GDB 调试 session 的最佳方法是什么?

bash - 为什么 bash 脚本变量不保存?

Windows Git Bash - ulimit - 打开的文件太多

c - 无论如何,我可以在不安装的情况下使用expect吗?

mysql - 如何在expect/TCL脚本中从转储文件创建MySQL数据库?

arrays - 将目录时间戳插入 bash 中按日期排序的数组