Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timeouting a while loop in Linux shell script

This works fine (infinite loop):

$ while TRUE; do printf ".";done

.............................................................................

I am trying to timeout this while loop with the timeout command. All these don't work:

$ timeout 5 while TRUE; do printf ".";done
$ timeout 5 "while TRUE; do printf ".";done"
$ timeout 5 "while TRUE; do printf \".\";done"
$ timeout 5 $(while TRUE; do printf ".";done)
$ timeout 5 $('while TRUE; do printf ".";done')

What is the correct way (if it exists)?

like image 761
Sopalajo de Arrierez Avatar asked Dec 18 '14 21:12

Sopalajo de Arrierez


Video Answer


1 Answers

I think that the solution to your problem is to execute another shell instance and pass proper commands to it. According to bash manual:

-c        If the -c option is present, then commands are read from the first non-option argument command_string.

Thus my solution would be something like that:

timeout 5 bash -c -- 'while true; do printf ".";done'

-- assures that the following arguments will be treated as non-option. And '' helps with passing " without unnecessary escaping

like image 100
luantkow Avatar answered Nov 15 '22 19:11

luantkow