使用bash中的read-and-expect自动响应



我想在提示用户输入姓名时自动执行该过程,它应该自动写入world

#!/bin/bash
fullname=""
read -p "hello" fullname
/usr/bin/expect -c "expect hello {send world}"
echo $fullname 

上面的代码仍在等待用户输入。我想得到如下行为:

hello
world

使用expect有可能实现这样的行为吗?如果是,如何?

EDIT:人们会期望send world将其结果存储在fullname变量中。所有的想法都是有fullname变量供以后使用

read -p "hello" fullname行是脚本暂停的地方。它将read用户输入并将其分配给fullname

下面的脚本将实现您的要求。

#!/bin/bash
fullname=$(echo hello | /usr/bin/expect -c  "expect hello {send world}")
echo "hello " $fullname

expect从stdin读取数据,因此我们可以使用echo将数据发送到它

然后expect的输出被分配给CCD_ 11

这里有一个你可能会觉得有用的教程链接。Bash Prog简介

通常需要驱动/自动化其他程序,如ftp、telnet、ssh或bash。使用bash来驱动预期脚本是可能的,但并不常见。这是一个预期的脚本,可以实现我认为你想要的:

[plankton@localhost ~]$ cat hello.exp
#!/usr/bin/expect
log_user 0
spawn read -p hello fn
expect {
        hello {
                send "worldr"
                expect {
                        world {
                                puts $expect_out(buffer)
                        }
                }
        }
}
[plankton@localhost ~]$ ./hello.exp
world

但正如您所看到的,仅仅执行puts world还有很长的路要走。

在bash中可以这样做。。。

$ read -p "hello" fullname <<EOT
> world
> EOT
$ echo $fullname
world

但再一次,还有很长的路要走

fullname=world

我不明白你为什么需要期望。为了满足您的要求,您所需要做的就是:

echo world | /path/to/your/script

这将在"fullname"变量中存储"world"。

最新更新