linux - count the number of attempts from an output -


this question in regard output of script, because need know how many attempts made..

## guess right number ##  #!/bin/bash clear  while :   echo "enter guessing number:"  read num  if [ $num -eq 47 ];  echo "that right number"  break  elif [ $num -le 47 ];  echo "print higher number"  elif [ $num -ge 47 ];  echo "print lower number"  fi  done 

and following output be:

enter guessing number:

23

print higher number

enter guessing number:

34

print higher number

enter guessing number:

45

print higher number

enter guessing number:

47

that right number

how write code display line stating how many attempts made reach correct answer?

you aren't far off.

this on bash incrementing variable called $attempts (which starts @ 1), each time wrong answer attempted.

the loop message uses $lastmsg variable make simple display relevant prompt each time.

#!/bin/bash guessno=47                                        # set number guess attempts=1                                        # initial attempts 1 while true;                                       # run forever until exit     clear     echo "$lastmsg"                               # display last message     read -p "enter guessing number" num     if [[ $num -eq "$guessno" ]];         echo "correct"         echo "it took "$attempts" attempt(s)"         exit                                       # exit program here     fi     if [[ $num -le "$guessno" ]];         lastmsg="print higher number"              # update $lastmsg         (( attempts ++ ))     elif [[ $num -ge "$guessno" ]];         lastmsg="print lower number"               # update $lastmsg         (( attempts ++ ))     fi    done 

note entire program took place inside endless loop, correct answer exiting program directly.


Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -