【问题标题】:Pause for loop until key is pressed暂停循环直到按键被按下
【发布时间】:2017-07-03 06:17:12
【问题描述】:

如何运行一个在每次迭代后暂停直到按键被按下的 for 循环? 例如,如果我想打印 file1、file2、file3 的行号,但只在按下一个键后继续:

for f in dir/file? ; do wc -l $f ; pause until key is pressed ; done

抱歉,如果这是微不足道的,我是编码新手。

【问题讨论】:

    标签: bash for-loop


    【解决方案1】:

    使用read 命令等待用户输入单个字符(-n1)

    read -p "Press key to continue.. " -n1 -s
    

    man 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
    
    -p      prompt output the string PROMPT without a trailing newline before
            attempting to read
    

    【讨论】:

      【解决方案2】:

      @Stewart:试试:

      cat script.ksh
      trap "echo exiting...; exit" SIGHUP SIGINT SIGTERM
      for file in /tmp/*
      do
              wc -l $file
      echo "Waiting for key hit.."
      read var
              if [[ -n $var ]]
              then
                      continue
              fi
      done
      

      这个脚本会一直运行,直到/除非系统得到一个信号来杀死它(例如--> cntl+c 等)。让我知道这是否有帮助。逻辑很简单,创建一个陷阱第一行脚本来处理用户的中断,然后创建一个 for 循环,它将查看包含所有文件的目录(您也可以根据需要进行更改)。然后根据您的帖子显示当前文件的 wc -l 。然后要求用户输入一个选项,如果用户输入任何内容,它将一次又一次地循环。

      【讨论】:

      • 这是我发现的唯一答案是 POSIX。即将进行测试。
      • @zaTricky,当然,请告诉我情况如何。
      • 工作 100% - 唯一的缺点是你 必须 按下回车键。我发现的所有其他“解决方案”都使用非 POSIX 标志(例如 -p、-s、-n)
      • @zaTricky,很高兴它对您有所帮助。请看这个stackoverflow.com/help/someone-answers
      猜你喜欢
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 2021-05-26
      • 2021-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-27
      相关资源
      最近更新 更多