发现这个有趣的脚本可以在终端内绘制雪花,但是……我希望有一个选项可以随时输入“q”来退出循环。这就是我所拥有的;
LINES=$(tput lines)
COLUMNS=$(tput cols)
declare -A snowflakes
declare -A lastflakes
clear
function move_flake() {
i="$1"
if [ "${snowflakes[$i]}" = "" ] || [ "${snowflakes[$i]}" = "$LINES" ]; then
snowflakes[$i]=0
else
if [ "${lastflakes[$i]}" != "" ]; then
printf "\033[%s;%sH \033[1;1H " ${lastflakes[$i]} $i
fi
fi
printf "\033[%s;%sH*\033[1;1H" ${snowflakes[$i]} $i
lastflakes[$i]=${snowflakes[$i]}
snowflakes[$i]=$((${snowflakes[$i]}+1))
}
while :
do
i=$(($RANDOM % $COLUMNS))
move_flake $i
for x in "${!lastflakes[@]}"
do
move_flake "$x"
done
sleep 0.1
done
这是我试图添加的;
echo "Type 'q' to exit out"
while read -n1 -r -p "want to exit the script?"
do
if [[ $REPLY == q ]];
then
break;
else
#whatever
fi
done
将其添加到函数内部,但只在最开始要求“q”。然后尝试在退出循环内添加实际脚本,并且只绘制一片雪花,然后再次询问我是否要退出……知道如何让它工作吗?
答案1
您可以在 shell 中这样做bash
:将sleep
命令替换为read
具有超时的命令,然后while
检查'q'
。请参阅
help read | less
这是我的版本的雪花秀,
#!/bin/bash
LINES=$(tput lines)
COLUMNS=$(tput cols)
declare -A snowflakes
declare -A lastflakes
clear
function move_flake() {
i="$1"
if [ "${snowflakes[$i]}" = "" ] || [ "${snowflakes[$i]}" = "$LINES" ]; then
snowflakes[$i]=0
else
if [ "${lastflakes[$i]}" != "" ]; then
printf "\033[%s;%sH \033[1;1H " ${lastflakes[$i]} $i
fi
fi
printf "\033[%s;%sH*\033[1;1H" ${snowflakes[$i]} $i
lastflakes[$i]=${snowflakes[$i]}
snowflakes[$i]=$((${snowflakes[$i]}+1))
}
while [ "$ans" != "q" ]
do
i=$(($RANDOM % $COLUMNS))
move_flake $i
for x in "${!lastflakes[@]}"
do
move_flake "$x"
done
read -sn 1 -t 0.1 ans
done