【问题标题】:Linux Script to execute something when F1 is hitter当 F1 被击中时执行某些东西的 Linux 脚本
【发布时间】:2014-02-23 22:30:38
【问题描述】:

我有这个脚本 start.sh

 #!/bin/bash
while[1]
do 
read -sn3 key
if [$key=="\033[[A"]
then
  ./test1
else
  ./test2
fi
done

我想设置一个永久循环检查是否按下 F1 键。如果按下执行 test1 否则 test2。我做了 start.sh 并在后台运行,以便其他程序可以运行。

我有错误 while [1] 命令未找到 意外标记“do”附近的语法错误 [f==\033]: 找不到命令

还有这个读取命令在哪里?我输入了哪个读,没找到。

另外,如果尝试 ./start.sh & 它会给出完全不同的行为。我输入一个密钥,它说找不到密钥。我虽然只是在后台运行脚本

【问题讨论】:

  • 你的shebang坏了,你是说#!/bin/bash吗?如果您使用 bash,请阅读 help while 以了解正确的语法或查看 stackoverflow.com/questions/10797835/while-vs-while-true
  • 一定要F1吗?使用 y/n、1/2、a/b 等非转义键会更容易
  • 是的,如果被终端捕获,F1 将不起作用。例如对于 XFCE 终端,F!带来帮助。如果是这种情况,您必须禁用它,以便将其传递给pts 设备。

标签: linux bash


【解决方案1】:

您的代码中有几个基本的语法问题(考虑在发布之前使用shellcheck 来清理这些东西),但该方法本身存在缺陷。点击“q”和“F1”会产生不同长度的输入。

这是一个脚本,它依赖于转义序列都来自同一个读取调用这一事实,这是肮脏但有效的:

#!/bin/bash
readkey() {
  local key settings
  settings=$(stty -g)             # save terminal settings
  stty -icanon -echo min 0        # disable buffering/echo, allow read to poll
  dd count=1 > /dev/null 2>&1     # Throw away anything currently in the buffer
  stty min 1                      # Don't allow read to poll anymore
  key=$(dd count=1 2> /dev/null)  # do a single read(2) call
  stty "$settings"                # restore terminal settings
  printf "%s" "$key"
}

# Get the F1 key sequence from termcap, fall back on Linux console
# TERM has to be set correctly for this to work. 
f1=$(tput kf1) || f1=$'\033[[A' 

while true
do
  echo "Hit F1 to party, or any other key to continue"
  key=$(readkey)
  if [[ $key == "$f1" ]]
  then
    echo "Party!"
  else
    echo "Continuing..."
  fi
done

【讨论】:

  • 不错!可能最好默认为xterm 转义序列而不是linux 或自己检查TERM。它应该比各种终端模拟器的数组更可靠地设置为 Linux 控制台。
  • @Graeme 问题的代码使用 Linux 控制台序列,所以很可能这就是他们的终端使用的。
【解决方案2】:

应该是

while :

while true

【讨论】:

    【解决方案3】:

    试试这个:

    #!/bin/bash
    
    while true
    do 
      read -sn3 key
      if [ "$key" = "$(tput kf1)" ]
      then
        ./test1
      else
        ./test2
      fi
    done
    

    使用tput 生成控制序列更加健壮,您可以在man terminfo 中看到完整列表。如果tput 不可用,您可以将$'\eOP' 用于大多数终端仿真器,或者将$'\e[[A' 用于Linux 控制台($ 是字符串所必需的,以使 bash 解释转义序列)。

    read 是一个bash 内置命令 - 试试help read

    【讨论】:

    • @lilzz tput 是使用terminfo 库生成控制序列的命令。这个想法是它可以与各种不同的终端一起工作,它位于 Debian/Ubuntu 上的 ncurses-bin 包中。如果没有,可以在这里使用控制序列 - invisible-island.net/xterm/ctlseqs/ctlseqs.html
    • 另外$()是命令替换,它是一种在另一个命令中使用stdout的方法。
    猜你喜欢
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多