I have the following loop which counts from 0 till 99:
#!/bin/bash
for ((i=0;i<100;i++));
do
echo $i
sleep 1
done
Is there a way to change the result of the output from terminal while this loop script is running. Lets say if I press letter k the loop automatically add 10 more number to the current number, so if we have 10 being displayed on the screen and we press K the loop should automatically change to 20! Thanks
As mentioned in comment you can use:
read -t 1 -n 1 key
which because of -t
option we can remove sleep
, so your script could be:
#!/bin/bash
for ((i=0; i<100; i++)); do
read -t 1 -n 1 key
if [ "$key" = "k" ]; then
i=$((i + 10))
fi
echo $i
done
But I think more portable could be:
#!/bin/bash
if [ -t 0 ]; then stty -echo -icanon -icrnl time 0 min 0; fi
keystroke=''
i=0
while [ $i -lt 100 ]; do
keystroke="$(dd bs=1 count=1 2>/dev/null)" # http://www.tldp.org/LDP/abs/html/
if [ "$keystroke" = "k" ]; then
i=$(( i + 10 ))
elif [ "$keystroke" = "q" ]; then
break
fi
i=$(( i + 1 ))
echo $i
sleep 1
done
if [ -t 0 ]; then stty sane; fi
exit 0
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加