Timeouting a while loop in Linux shell script

孤者浪人 提交于 2019-12-23 11:02:15

问题


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)?


回答1:


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



来源:https://stackoverflow.com/questions/27555727/timeouting-a-while-loop-in-linux-shell-script

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