简体   繁体   中英

change a counter according to a output function in a while loop - in bash

I have a function returning randomly R or L. I want to change a counter according to the output of this function: I want to increase the counter when R appear and decrease it when L appear.

My problems: the counter doesn't change according to the output function (R or L) and the counter decrease only or increase only.

#GetsomeLoR is a function returning R or L
function GetsomeLoR() {
  set -- "R" "L"
  eval echo \$$(expr $RANDOM % 2 + 1)
  sleep 0.015
}

return_var=$(GetsomeLoR) # return the output of the function named GetsomeLoR
counter="1" 
number_max="60"

while [ $counter -lt $number_max ]; do
    GetsomeLoR && sleep 0.1 
    if [[ $return_var == "L" ]]; then
        counter=$[$counter-1]
        echo $counter increase
    elif [[ $return_var == "R" ]]; then
        counter=$[$counter+1]
        echo $counter decrease
    else
        echo error_buddy
    fi
done

My questions: How to change a counter according to the output function named GetsomeLoR ? Thank you!

You're not capturing the output of GetsomeLoR in your loop. Thus you're using the single value it returned on the first call outside your loop.

while [ $counter -lt $number_max ]; do
    return_var=$(GetsomeLoR)
    sleep 0.1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM