How to timeout a group of commands in Bash

◇◆丶佛笑我妖孽 提交于 2020-06-08 05:19:05

问题


I am fiddling with Linux command "timeout": it simply stops a long running command after a given seconds. But I would like to timeout not only a command, but a group of commands. I can group command in two way ( ) and { ;} however none of the following works:

timeout 1 { sleep 2; echo something; }
timeout 1 ( sleep 2; echo something )

How can I do that with grouping?


回答1:


timeout is not a shell utility and it does not do shell-style processing. It must be given one single command to execute. That command, though, can have any number of arguments. Fortunately, one of the commands that you can give it is bash:

timeout 1 bash -c '{ sleep 2; echo something; }'

Of course, in this form, the braces are now superfluous:

timeout 1 bash -c 'sleep 2; echo something'

Here, bash is the command that timeout executes. -c and sleep 2; echo something are argument to that command.




回答2:


timeout 1 sh -c "sleep 2; echo something"



回答3:


You can also use the Here Document EOF method to create the multi-line script on the fly. The main advantage of it, is that you can use double quotes without escaping it:

timeout 1s bash <<EOF
    sleep 2s
    echo "something without escaping double quotes"  
EOF

Notes:

  1. The EOF closure must not follow spaces/tabs, but be at the start of the last line.
  2. Make sure you've exported local functions with export -f my_func or set -o allexport for all functions (before declaring them). This is relevant for previous answers as well, since calling bash/sh run the process in new session, unaware to local environment functions.


来源:https://stackoverflow.com/questions/37981492/how-to-timeout-a-group-of-commands-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!