等待命令在 bash 脚本中返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4189136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Waiting for a command to return in a bash script
提问by Ankur Agarwal
What I am trying to do:
我正在尝试做的事情:
My bash shell script contains a modprobe -a $modulename. Sometimes loading that module fails and the modprobestatement just gets stuck. It never returns and hence, my script is stuck too.
我的 bash shell 脚本包含一个modprobe -a $modulename. 有时加载该模块会失败,并且modprobe语句会卡住。它永远不会返回,因此,我的脚本也被卡住了。
What I want to do is this: Call modprobe -a $modulename, wait for 20 secs and if the command does not return and script remains stuck for 20 secs, call that a failure and exit !
我想要做的是:调用modprobe -a $modulename,等待 20 秒,如果命令没有返回并且脚本保持卡住 20 秒,则称其为失败并退出!
I am looking at possible options for that. I know timeoutis one, which will allow me to timeout after certain time. So I am thinking :
我正在寻找可能的选择。我知道timeout是一个,它可以让我在一定时间后超时。所以我在想:
timeout -t 10 modprobe -a $modulename
if [ "$?" -gt 0 ]; then
echo "error"
exit
fi
timeout -t 10 modprobe -a $modulename
if [ "$?" -gt 0 ]; then
echo "error"
exit
fi
But the problem is $? can be > 0 , not just because of timeout, but because of an error while loading the module too and I want to handle the two cases differently.
但问题是$? 可以 > 0 ,不仅仅是因为超时,还因为加载模块时出错,我想以不同的方式处理这两种情况。
Any ideas using timeout and without using timeout are welcome.
欢迎任何使用超时和不使用超时的想法。
回答by thkala
According to timeout(1), timeout exits with a specific code (124 in my case) if the command times out. It's highly unlikely that modprobe would exit with that code, so you could probably check specifically for that by changing your condition:
根据 timeout(1),如果命令超时,则 timeout 会以特定代码(在我的情况下为 124)退出。modprobe 不太可能随该代码退出,因此您可以通过更改条件来专门检查:
...
...
RET="$?"; if [[ "$RET" = "124" ]]; then echo timeout; OTHER COMMAND; elif [[ "$RET" -gt 0 ]]; then echo error; exit; fi
RET="$?"; 如果 [[ "$RET" = "124" ]]; 然后回声超时;其他命令;elif [[ "$RET" -gt 0 ]]; 然后回显错误;出口; 菲
BTW, it is a verygood practice to assign "$?" to a variable immediately after your command. You will avoid a lot of grief later...
顺便说一句,这是一个非常好的做法,以分配“$?” 在您的命令之后立即到一个变量。以后你会避免很多悲伤......
If you really do need to make sure, you can check the modprobe source code to see what exit codes it produces, since apparently it was not deemed important enough to mention in its manual page...
如果您确实需要确保,您可以检查 modprobe 源代码以查看它产生的退出代码,因为显然它被认为不够重要,无法在其手册页中提及...
回答by Andrew Stringer
consider using "expect", you can set a timeout as well as running different command depending on the outcome of the modprobe.
考虑使用“expect”,您可以设置超时以及根据 modprobe 的结果运行不同的命令。
Regards, Andrew.
问候,安德鲁。

