How to timeout a group of commands in Bash
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.
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.