Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to timeout a group of commands in Bash

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?

like image 670
Konstantin Avatar asked Jun 23 '16 02:06

Konstantin


1 Answers

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.
like image 50
Noam Manos Avatar answered Sep 29 '22 14:09

Noam Manos