我正在尝试执行一个脚本,该脚本执行一个 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
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
}
然后添加lassign
和if
命令。
关于linux - 如何在 expect shell 脚本中获取生成进程的退出代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23614039/