需要使用expect生成源shell脚本

时间:2013-07-12 14:36:14

标签: bash environment-variables expect interaction

我正在使用expect来自动化一些bash脚本。一切正常,直到我需要执行一个源脚本;然后我得到这个错误:

couldn't execute "source setNAME.sh": no such file or directory
while executing
"spawn "source setNAME.sh""
(file "./setNAME.exp" line 2)

我以一种基本的方式使用expect(spawn / expect / send / interact);问题出在spawn上。让我展示一个非常简单的例子:

脚本读取名称,回显值并以'NAME'的形式导出到环境:

/home/edu/scripts [] cat setNAME.sh
#!/bin/bash
echo "Your name?"
read name
export NAME=$name
echo "Provided NAME is $name"

如果使用'source'执行,则输入值将作为环境变量导出。正是我需要的:

/home/edu/scripts [] source setNAME.sh
Your name?
Dennis
Provided NAME is Dennis

/home/edu/scripts [] echo $NAME
Dennis

让我们使用expect避免交互,将'edu'设置为名称:

/home/edu/scripts [] cat setNAME.exp
#!/usr/bin/expect
spawn setNAME.sh
expect "Your name?"
send edu\r
interact

/home/edu/scripts [] setNAME.exp
spawn setNAME.sh
Your name?
edu
Provided NAME is edu

/home/edu/scripts [] echo $NAME
Dennis

但显然,这个名字仍然是Dennis:'edu'显示在sh脚本输出中但未导出为NAME,因为期望脚本生成不带源的setNAME.sh脚本(或脚本之前的点)。

问题在于我不能这样做,因为我在开头就收到了错误评论。

任何解决/提供这种需求的想法?

在我的情况下,脚本要复杂得多,其他解决方案也无效,例如:

source script.sh << EOF
<option1>
<option2>
...
EOF

这就是我试图使用期待的原因......

非常感谢!

1 个答案:

答案 0 :(得分:2)

source是一个内置的shell,而不是系统命令,因此您首先需要生成一个shell,然后将source命令发送给它。那个shell将具有NAME变量

中的值