1

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

1
  • You could look at trap to trap certain signals or reading user input ( read command ) in your script and modify your script to act according to the input. – rahul Apr 4 '15 at 18:16
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.