Reputation: 207
Is there a way to change the output of a script while it is running? Lets say I have a script called "numbers" and it is running. The script uses this loop to print numbers from 1 to 49:
for ((a=1; a<50; a++))
do
echo $a
sleep 1
done
How can I change the output of this loop while it is running? Let's say if I press a or b during the running, it should subtract 1 from the result.
Upvotes: 0
Views: 145
Reputation: 77137
As noted in the comments there is no time to do anything during so short a run. But if I make the run longer and slower I can demonstrate something similar to what you're asking.
declare -i a b c # Ensure these values are treated as integers
b=1
for ((a=0; a < 10**6; a+=b)); do
read -s -N1 -t.3 c && b=c
printf '%d...' "$a"
done
echo
Breakdown of read
arguments:
read -s # Don't echo output
-N1 # Read one character of input*
-t.3 # Wait for .3 seconds before giving up
c &&
b=c # If read was successful, assign value to c, then b
Here's some craziness. Enjoy:
declare -i a b
b=1
for ((a=0; a < 10**6; a+=b)); do
if read -s -N1 -t.01 c; then
case $c in
j) b=b+1;;
k) b=b-1;;
esac
fi
printf '%d...' "$a"
done
echo
*I noticed that bash v3 seems to use read -n1
and v4 read -N1
.
Upvotes: 2