gpt4 book ai didi

当 F1 被击中时执行某些事情的 Linux 脚本

转载 作者:太空狗 更新时间:2023-10-29 11:19:19 27 4
gpt4 key购买 nike

我有这个脚本 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 并在后台运行,以便其他程序可以运行。

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

此外,此读取命令位于何处?我输入 which read,它没有找到它。

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

最佳答案

您的代码中存在几个基本的语法问题(考虑在发布前使用 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

关于当 F1 被击中时执行某些事情的 Linux 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21975559/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com