问题
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:
- The EOF closure must not follow spaces/tabs, but be at the start of the last line.
- Make sure you've exported local functions with
export -f my_func
orset -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