【问题标题】:how to stop a bash programm (while loop) when press key or combination? [duplicate]按下键或组合时如何停止bash程序(while循环)? [复制]
【发布时间】:2018-08-17 02:09:14
【问题描述】:

我有一个while循环,我想在用户按下键盘上的字母“s”时停止它。

我应该使用“trap”和使用相对信号来处理问题,默认情况下,该块具有组合“ctrl + c”,但按“s”应该具有相同的效果。

(我不必使用命令读取)

在哪里放置命令?

你能解释一下吗?

谢谢

代码:

!/bin/bash

while true

do

echo text text text text

done

【问题讨论】:

标签: bash loops signals


【解决方案1】:

我不知道你为什么不想使用read,因为它很简单

#! /bin/bash

while :
do
    echo "text text text"
    read -t 0.3 -n 1 k
    [[ "$k" == 's' ]] && break
done

【讨论】:

    【解决方案2】:

    按照Aserre 所说的:

    #!/bin/bash
    
    if [ -t 0 ]; then stty -echo -icanon -icrnl time 0 min 0; fi
    
    keypress=''
    while [ "$keypress" != "s" ]; do
      echo text text text
      keypress="`cat -v`"
    done
    
    if [ -t 0 ]; then stty sane; fi
    

    【讨论】:

      猜你喜欢
      • 2017-05-23
      • 2015-03-25
      • 2019-04-02
      • 1970-01-01
      • 2015-08-06
      • 2021-08-18
      • 2015-07-19
      • 1970-01-01
      • 2019-05-20
      相关资源
      最近更新 更多