在Linux shell脚本中计时一段时间

Sop*_*rez 5 linux loops timeout

这工作正常(无限循环):

$ while TRUE; do printf ".";done
Run Code Online (Sandbox Code Playgroud)

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

我想超时while looptimeout命令.所有这些都不起作用:

$ 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')
Run Code Online (Sandbox Code Playgroud)

什么是正确的方法(如果存在)?

lua*_*kow 13

我认为你的问题的解决方案是执行另一个shell实例并将适当的命令传递给它.根据bash手册:

-c        If the -c option is present, then commands are read from the first non-option argument command_string.
Run Code Online (Sandbox Code Playgroud)

因此,我的解决方案将是这样的:

timeout 5 bash -c -- 'while true; do printf ".";done'
Run Code Online (Sandbox Code Playgroud)

--确保以下参数将被视为非选项.并且''有助于传递"而不会有不必要的逃避


con*_*use 5

至少 bash 的替代方案是这样的:

start=$EPOCHSECONDS
while <condition>
do
  sleep .2  # (or whatever loop body you have

  if (( EPOCHSECONDS-start > 5 )); then break; fi
done
Run Code Online (Sandbox Code Playgroud)

它不像那样简洁timeout,但它是一个全内置的,有它自己的优点。