1

I have a bash script which run a command to get its result and do something depends on the result. Here is the script:

#!/bin/bash
commandResult=$(($myCommand) 2>&1)
if [[ "$commandResult" == *Error* ]]; then 
    x="failed"
else
    x="success"
fi
echo $x
exit 0;

There is no problem with this script, the issue is when I try to kill $myCommand in the middle of running the script via kill -9 $myCommand in command line, the $commandResult will be null and the "success" will be printed.

How could I put the kill result in the $commandResult or any other way to find out if process killed in this script?

Any help would be much appreciated.

4

1 回答 1

3

您应该检查命令的退出代码,而不是其输出到标准错误。myCommand成功时应以 0 退出,失败时应退出一些非零代码。如果通过kill命令杀死它,它的退出代码将自动为 128+n,其中 n 是您用来杀死它的信号。然后你可以测试成功

if myCommand; then
    echo success
    exit 0
else
    status=$?
    echo failure
    exit $status
fi

此外,您可能不需要使用kill -9. 开始kill(发送更温和的TERM信号);如果这不起作用,请升级到kill -2( INT,相当于 Ctrl-C)。

于 2013-05-20T15:06:18.660 回答