Bash: How to end infinite loop with any key pressed?

前端 未结 6 734
长发绾君心
长发绾君心 2020-11-30 03:16

I need to write an infinite loop that stops when any key is pressed.

Unfortunately this one loops only when a key is pressed.

Ideas please?

#         


        
6条回答
  •  渐次进展
    2020-11-30 03:51

    I found this forum post and rewrote era's post into this pretty general use format:

    # stuff before main function
    printf "INIT\n\n"; sleep 2
    
    INIT(){
      starting="MAIN loop starting"; ending="MAIN loop success"
      runMAIN=1; i=1; echo "0"
    }; INIT
    
    # exit script when MAIN is done, if ever (in this case counting out 4 seconds)
    exitScript(){
        trap - SIGINT SIGTERM SIGTERM # clear the trap
        kill -- -$$ # Send SIGTERM to child/sub processes
        kill $( jobs -p ) # kill any remaining processes
    }; trap exitScript SIGINT SIGTERM # set trap
    
    MAIN(){
      echo "$starting"
      sleep 1
    
      echo "$i"; let "i++"
      if (($i > 4)); then printf "\nexiting\n"; exitScript; fi
    
      echo "$ending"; echo
    }
    
    # main loop running in subshell due to the '&'' after 'done'
    { while ((runMAIN)); do
      if ! MAIN; then runMain=0; fi
    done; } &
    
    # --------------------------------------------------
    tput smso
    # echo "Press any key to return \c"
    tput rmso
    oldstty=`stty -g`
    stty -icanon -echo min 1 time 0
    dd bs=1 count=1 >/dev/null 2>&1
    stty "$oldstty"
    # --------------------------------------------------
    
    # everything after this point will occur after user inputs any key
    printf "\nYou pressed a key!\n\nGoodbye!\n"
    

    Run this script

提交回复
热议问题