mun*_*ish 16 linux bash solaris exit background-process
#!/bin/bash
function back()
{
sleep $1
exit $2
}
back $1 $2 &
b=$!
if `wait $!`;then
echo success
else
echo failure
fi
Run Code Online (Sandbox Code Playgroud)
bash-3.00# ./back 300 0
failure
bash-3.00# ./back 300 1
failure
Run Code Online (Sandbox Code Playgroud)
success当我发送 0 时,我期待退出状态,但我仍然收到failure.
此外,wait不等待 300 秒。相反,我立即收到了消息。我假设$!是$$我脚本中的直接子代。不是吗?
是否可以捕获等待的退出状态exit_status=$(wait $!)?
if ! ((exit_status));then
echo sucess
else
failure
fi
Run Code Online (Sandbox Code Playgroud)
bah*_*mat 21
问题是您wait在子shell中发出:
if `wait $!`;then
Run Code Online (Sandbox Code Playgroud)
因为wait是内置命令,而不是命令,它在subshell上运行,而不是在您当前的 shell 上运行。
您会看到但不会看到的输出是:
wait: pid 12344 is not a child of this shell
Run Code Online (Sandbox Code Playgroud)
...返回状态为 1。
要执行测试,您需要在不使用子shell 的情况下进行。
#!/bin/bash
function back()
{
sleep $1
exit $2
}
back $1 $2 &
b=$!
wait $b && echo success || echo failure
Run Code Online (Sandbox Code Playgroud)
这给出了您期望的结果,并按照您的期望等待:
$ time ./test.sh 3 0
success
./test.sh 3 0 0.00s user 0.01s system 0% cpu 3.012 total
$ time ./test.sh 3 1
failure
./test.sh 3 1 0.00s user 0.01s system 0% cpu 3.012 total
Run Code Online (Sandbox Code Playgroud)
您可以使用$?以下命令检查任何命令的退出状态:
$ /bin/true
$ echo $?
0
$ /bin/false
$ echo $?
1
Run Code Online (Sandbox Code Playgroud)
您的脚本中还有其他一些错误。您的#!线路格式错误,我已修复。您分配$!给$b,但不要使用$b。
phe*_*mer 12
去掉反引号。
wait照原样,您正在一个子shell 中执行,该子shell 无权访问父shell 的作业,因此它将立即失败。
如果您想要退出状态,请$?在等待后立即获取值。
command_here &
wait
status=$?
Run Code Online (Sandbox Code Playgroud)