在某些条件下调用自身的功能,BASH

时间:2017-10-28 18:07:46

标签: bash

function Lab()
{
local result=0
echo

echo 'Please enter your overall percentage for your labs (40% possibility)'
read result

if [ $result != 40 ] || [ $result -lt 0 ]
then
    echo "You have entered a invalid value, please try again."
    Lab #I thought this would call the function again, resetting itself
else
    return $result
fi
}

我基本上希望这个函数只能从0-40中取值。除此之外的任何值都应该导致函数重新启动,直到给出真值。我对bash很陌生,而且我在过去的一天里一直在努力解决这个问题。如果有人有任何建议可以推动我朝着正确的方向发展,那就太棒了!

1 个答案:

答案 0 :(得分:3)

不需要递归;只需使用while循环。此外,函数的return值不用于返回数据,仅用于返回退出状态。设置全局变量,或将结果写入标准输出。

lab () {
  echo
  echo 'Please enter your overall percentage for your labs (40% possibility)'
  IFS= read -r result

  while [ "$result" -gt 40 ] || [ "$result" -lt 0 ]; do
    echo "You have entered a invalid value, please try again."
    IFS= read -r result
  done

  echo "$result"
}