0

我正在尝试在 bash 中进行直到仿真,但没有工作。代码如下

# an emulation of the do-until loop

do_stuff() {

echo "Enter password"
read password         

if [[ $password != "theflow" ]]
   then
     echo " Sorry, try again."
fi   
}

do_stuff

until (( $password == "theflow" ))
 do
  do_stuff
done
4

1 回答 1

2

与其$password在两个不同的地方进行比较,我认为使用函数的返回码来指示检查是否成功会更有意义:

check_password () {
  read -rsp 'Enter password: ' password

  if [[ $password != 'theflow' ]]; then
    echo 'Sorry, try again.' >&2
    return 1
  fi

  return 0
}

那么你的until循环可以是:

until check_password; do
  :
done

它将继续调用check_password,直到它返回0(成功)。

根据评论中的建议,我对您的代码进行了更多更改(谢谢!):

我曾经read -rsp做过以下事情:

  • -r禁用\转义字符的解释(你几乎总是想要这个)
  • -s静音模式 - 不回显字符
  • -p 'Enter password: '显示提示,无需echo单独

我还使用>&2.

请注意,这(( $password == "theflow" ))不会像您预期的那样运行,因为比较是在算术上下文中执行的。您应该使用[[来比较字符串。

于 2020-02-28T11:49:43.963 回答