linux - 如何在 expect shell 脚本中获取生成进程的退出代码?

标签 linux bash shell unix expect

我正在尝试执行一个脚本,该脚本执行一个 EXPECT 脚本和一个包含退出代码的派生进程。但是我无法将衍生进程的退出代码获取到主脚本。我的成功总是零。

期望脚本是:

 [Linux Dev:anr ]$ cat testexit.sh
 #!/bin/bash
 export tmp_script_file="/home/anr/tmp_script_temp.sh"
 cp /home/anr/tmp_script $tmp_script_file
 chmod a+x $tmp_script_file
 cat $tmp_script_file
 expect << 'EOF'
 set timeout -1
 spawn  $env(tmp_script_file)
 expect {
 "INVALID "  { exit 4 }
 timeout     { exit 4 }
 }
 EOF
 echo "spawned process status" $?
 rm -f $tmp_script_file
 echo "done"

衍生脚本:

 [Linux Dev:anr ]$ cat tmp_script
 exit 3

Expect 脚本的执行:

 [Linux Dev:anr ]$ ./testexit.sh
 exit 3
 spawn /home/anr/tmp_script_temp.sh
 spawned process status 0
 done

问题是我无法获得生成的退出返回代码来期望脚本。我希望生成脚本的退出代码 3 到主脚本,并且主脚本应该以退出代码 3 退出。

请帮助我将生成的退出代码获取到主脚本。

最佳答案

您可以使用 wait 命令获取衍生进程的退出状态:

expect <<'END'
log_user 0
spawn sh -c {echo hello; exit 42}
expect eof
puts $expect_out(buffer)

lassign [wait] pid spawnid os_error_flag value

if {$os_error_flag == 0} {
    puts "exit status: $value"
} else {
    puts "errno: $value"
}
END
hello

exit status: 42

来自expect man page

wait [args]

delays until a spawned process (or the current process if none is named) terminates.

wait normally returns a list of four integers. The first integer is the pid of the process that was waited upon. The second integer is the corresponding spawn id. The third integer is -1 if an operating system error occurred, or 0 otherwise. If the third integer was 0, the fourth integer is the status returned by the spawned process. If the third integer was -1, the fourth integer is the value of errno set by the operating system. The global variable errorCode is also set.


改变

expect {
"INVALID "  { exit 4 }
timeout     { exit 4 }
}

expect {
    "INVALID "  { exit 4 }
    timeout     { exit 4 }
    eof
}

然后添加lassignif 命令。

关于linux - 如何在 expect shell 脚本中获取生成进程的退出代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23614039/

相关文章:

c++ - GCC 4.9.1 在 RHEL 6.0 上编译失败,编译错误在 "libsanitizer"

string - Bash- 打乱字符串中包含的字符

linux - 打印包含某个单词的所有行恰好 k 次

linux - 无法检查目录是否存在 shell 脚本

linux - 如果以64位代码使用32位int 0x80 Linux ABI,会发生什么情况?

linux - 在 bash 脚本中循环

linux - 拒绝访问权限-apache、linux

linux - 当使用 ffmpeg 将脚本传输到 bash 时,第一个字符消失

linux - 终端选项卡中带有符号链接(symbolic link)的 pwd 的奇怪行为

Linux - 通过将最后一个连字符替换为 '##' 来重命名所有文件