【发布时间】:2013-07-12 14:36:13
【问题描述】:
我正在使用 expect 来自动化一些 bash 脚本。一切正常,直到我需要执行源脚本;然后我得到这个错误:
couldn't execute "source setNAME.sh": no such file or directory
while executing
"spawn "source setNAME.sh""
(file "./setNAME.exp" line 2)
我以一种基本的方式使用期望(spawn/expect/send/interact);问题在于产卵。让我举一个非常简单的例子:
读取名称、回显值并作为“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
这就是我尝试使用期望的原因...
非常感谢!
【问题讨论】:
-
第一个问题很好,抱歉,不是专家,但你试过
spawn source setname.csh吗?祝你好运。 -
是的,我做的第一件事当然是(对不起,我解释得不好)。我不明白原因,但肯定有一个。我也尝试使用引号:spawn "source
-
尝试打开所有的 shell 调试级别,在 csh 中它是
set -vx(可能与预期类似)。然后您可以看到每一行在分配变量值之前和之后执行。这可能会给你一个线索。由于这是一个简单的脚本,您也可以尝试在bash中实现这么多,用这些结果编辑您的问题并用bash标记。那时你会得到更多的帮助。祝你好运。 -
好的,我使用 bash 而不是 csh 修改了原始问题。我尝试了 sh/ksh/bash,结果相同。希望新标签有助于找到解决方案。我调试(在 ksh/bash 中设置 -x,在 csh 中设置 -xv)但不知道发生了什么。
标签: bash environment-variables expect interaction