使用任何特定键终止包含长时间睡眠和其他内容的 BASH For 循环

使用任何特定键终止包含长时间睡眠和其他内容的 BASH For 循环

我有一个 bash 脚本

  • 有一个 for 循环,它会迭代很多次,并在迭代之间休眠,可能会休眠很长时间。那么它

  • 将结果写入文件,然后终止。

有时,我会在许多循环迭代完成之前得到所需的结果。

在这些情况下,我需要脚本break退出 for 循环,而它是

  • 做事,或者

  • 睡眠

以这种方式,它将在 for 循环之后继续执行脚本的其余部分,该循环正在写入迄今为止收集的数据的报告文件。

我希望使用组合键(例如 CTRL+Q)来break跳出 for 循环。

脚本如下所示:

#!/bin/bash

for (( c=0; c<=$1; c++ ))
do  

# SOME STUFF HERE
#  data gathering into arrays and other commands here etc

# sleep potentially for a long time
sleep $2

done

#WRITE REPORT OUT TO SCREEN AND FILE HERE

答案1

我已经有一段时间没有接触过此类任务了,但我记得这样的事情曾经有效:

#!/bin/bash

trap break INT

for (( c=0; c<=$1; c++ ))
do  

# SOME STUFF HERE
#  data gathering into arrays and other commands here etc

    echo loop "$c" before sleep

    # sleep potentially for a long time
    sleep "$2"

    echo loop "$c" after sleep

done

#WRITE REPORT OUT TO SCREEN AND FILE HERE

echo outside

这个想法是使用Ctrl-C来打破循环。该信号 (SIGINT) 被陷阱捕获,从而中断循环并让脚本的其余部分继续执行。

例子:

$ ./s 3 1
loop 0 before sleep
loop 0 after sleep
loop 1 before sleep
^Coutside

如果您对此有任何问题,请告诉我。

答案2

最简单的方法是使用Ctrl+C,因为默认情况下它会发出INT信号,这会导致大多数应用程序停止,并且您可以在 shell 中捕获它。

要立即中断整个循环,您可以在子 shell 中运行它,并exit在中断时运行它。这里,陷阱只在子shell中设置,并且只有它退出。

#!/bin/bash

(
trap "echo interrupted.; exit 0" INT
while true; do
        echo "running some task..."
        some heavy task 
        echo "running sleep..."
        sleep 5;
        echo "iteration end."
done
)

echo "script end."

答案3

在某些情况下,最好有一个不中断“SOME STUFF HERE”并且仅在 shellscript 等待时中断的解决方案。

然后您可以使用带有一些选项的 shell 内置命令read来代替sleep.

试试这个shell脚本,

#!/bin/bash

echo "Press 'q' to quit the loop and write the report"
echo "Press 'Enter' to hurry up (skip waiting this time)"

for (( c=0; c<=$1; c++ ))
do  

 echo "SOME STUFF HERE (pretending to work for 5 seconds) ..."
 sleep 5
 echo "Done some stuff"

#  data gathering into arrays and other commands here etc

# sleep potentially for a long time

#sleep $2
 read -n1 -st$2 ans
 if [ "$ans" == "q" ]
 then
  break
 elif [ "$ans" != "" ]
 then
  read -n1 -st$2 ans
 fi
done

echo "WRITE REPORT OUT TO SCREEN AND FILE HERE"

您可以read使用以下命令找到有关的详细信息help read

      -n nchars return after reading NCHARS characters rather than waiting
            for a newline, but honor a delimiter if fewer than
            NCHARS characters are read before the delimiter
      -s    do not echo input coming from a terminal
      -t timeout    time out and return failure if a complete line of
            input is not read within TIMEOUT seconds.  The value of the
            TMOUT variable is the default timeout.  TIMEOUT may be a
            fractional number.  If TIMEOUT is 0, read returns
            immediately, without trying to read any data, returning
            success only if input is available on the specified
            file descriptor.  The exit status is greater than 128
            if the timeout is exceeded

相关内容