shell - 需要从 expect 脚本返回生成进程的退出代码

标签 shell tcl expect

我有下面的期望脚本

expect -c "
spawn tdwallet add $StringName
expect \"^Enter\"
send \"Krishna123\r\"
"

if [ $? != 0 ]; then
   echo "Failed to Add a String $StringName."
else
   echo "\"add <string>\" ==> [OK]"
fi

我尝试修改 expect 脚本,即在“发送”之后添加一些行

expect -c "
spawn tdwallet add $StringName
expect \"^Enter\"
send \"Krishna123\r\"
expect eof
catch wait reason
exit [lindex $reason 3]
"

但无论进程失败/成功,它总是返回一个非零值。

您能给我一些指示,以便在进程失败/成功时识别正确的退出代码吗。

提前致谢

问候,
斯里克里希纳埃拉。

最佳答案

问题是 $reason 正在被您的 shell 替换(而不是预期)。此外,它可能被替换为空字符串,这会导致语法错误。解决这个问题最快的方法是在 $ 前面加一个反斜杠,如下所示:

expect -c "
spawn tdwallet add $StringName
expect \"^Enter\"
send \"Krishna123\r\"
expect eof
catch wait reason
exit [lindex \$reason 3]
"

OTOH,现在您已经达到了这种复杂程度,最好将该脚本放在一个单独的文件中,这样您就可以减少反斜杠的数量。在那一点上,您然后切换到将要添加的东西作为命令行参数传递。

因此,在 addWallet.exp 中你有这个:

spawn tdwallet add [lindex $argv 0]
expect "^Enter"
send "Krishna123\r"
expect eof
catch wait reason
exit [lindex $reason 3]

然后你的主要脚本是这样的:

expect addWallet.exp $StringName

使用起来更容易!

关于shell - 需要从 expect 脚本返回生成进程的退出代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5806740/

相关文章:

linux - 如何使用expect只记录命令的输出

在expect命令中进行Bash数组变量扩展

mysql - 如何在 Windows 中使用命令提示符从服务器下载 mysql 数据库

perl - 在远程机器上查找/tmp 中的可用空间

variables - 在 tcl 中,当变量名称由另一个变量组成时,无法读取该变量

linux - 期望脚本在 2 个服务器之间远程 SSH

超时运行的 Bash 脚本不会在 SIGINT 上退出

java - 如何从 Java 调用 Linux shell 命令

regex - 在 tcl 中的正则表达式中传递变量

git - 运行 Git GUI 时找不到 tcl.init 时出错