我有这个脚本start.sh
#!/bin/bash while[1] do read -sn3 key if [$key=="\033[[A"] then ./test1 else ./test2 fi done
我想设置一个永久循环检查,看F1键是否按下。 如果按下,执行test1 else test2。 我做了start.sh&在后台运行,所以其他程序可以运行。
我得到错误,而[1]命令没有发现语法错误附近的意想不到的令牌'做'[F == \ 033]:找不到命令
这个读命令也位于哪里? 我input哪个阅读,它没有find它。
此外,如果尝试./start.sh它给出完全不同的行为。 我input一个密钥,它说没有find密钥。 我只是在后台运行脚本
在你的代码中有几个基本的语法问题(考虑在发布之前使用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
尝试这个:
#!/bin/bash while true do read -sn3 key if [ "$key" = "$(tput kf1)" ] then ./test1 else ./test2 fi done
使用tput
生成控制序列更加健壮,可以在man terminfo
看到完整的列表。 如果tput
不可用,则可以对大多数终端仿真器使用$'\eOP'
,对于Linux控制台可以使用$'\eOP'
$'\e[[A'
(对于使用字符串来使bash解释转义序列而言, $
是必需的)。
read
是一个bash
内建命令 – 尝试help read
。