在 bash 中使用读取和期望自动响应
Automate response with read and expect in bash
我想在提示用户输入他的名字时自动执行该过程,它应该自动写入 world
。
#!/bin/bash
fullname=""
read -p "hello" fullname
/usr/bin/expect -c "expect hello {send world}"
echo $fullname
上面的代码仍在等待用户输入。我想获得如下行为:
hello
world
是否可以使用 expect
实现此类行为?如果是,如何?
编辑: 人们会期望 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
从标准输入读取,因此我们可以使用 echo
将数据发送给它。
然后将expect的输出赋值给fullname
.
这里有一个 link 教程,您可能会觉得有用。 Bash Prog Intro
通常期望 drives/automates 其他程序,例如 ftp、telnet、ssh 甚至 bash。使用 bash 来驱动 expect 脚本是可能的,但不是典型的。这是一个 expect 脚本,可以执行我认为您想要的操作:
[plankton@localhost ~]$ cat hello.exp
#!/usr/bin/expect
log_user 0
spawn read -p hello fn
expect {
hello {
send "world\r"
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
我完全不明白您为什么需要 expect。为了满足您的要求,您只需:
echo world | /path/to/your/script
这会将 "world" 存储在 "fullname" 变量中。
我想在提示用户输入他的名字时自动执行该过程,它应该自动写入 world
。
#!/bin/bash
fullname=""
read -p "hello" fullname
/usr/bin/expect -c "expect hello {send world}"
echo $fullname
上面的代码仍在等待用户输入。我想获得如下行为:
hello
world
是否可以使用 expect
实现此类行为?如果是,如何?
编辑: 人们会期望 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
从标准输入读取,因此我们可以使用 echo
将数据发送给它。
然后将expect的输出赋值给fullname
.
这里有一个 link 教程,您可能会觉得有用。 Bash Prog Intro
通常期望 drives/automates 其他程序,例如 ftp、telnet、ssh 甚至 bash。使用 bash 来驱动 expect 脚本是可能的,但不是典型的。这是一个 expect 脚本,可以执行我认为您想要的操作:
[plankton@localhost ~]$ cat hello.exp
#!/usr/bin/expect
log_user 0
spawn read -p hello fn
expect {
hello {
send "world\r"
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
我完全不明白您为什么需要 expect。为了满足您的要求,您只需:
echo world | /path/to/your/script
这会将 "world" 存储在 "fullname" 变量中。