循环直到用户在 sh 文件中按下“C”

循环直到用户在 sh 文件中按下“C”

我想要的是如下:

首先,当用户运行.sh 文件时,它会显示以下内容:

Review id:
You id is:XXX000YYY
Do you want to change it?[Press Y to change, C to continue]:

现在,如果用户按下Y,则让他更改 ID 并再次显示,并重复此操作,直到用户按下C继续。如何在 shell 脚本中执行此操作?


我尝试按照以下方法操作,但不知道在 if 条件下该写什么???

while :
do
  echo "Enter id:"
  read line
  echo "Your id: $line"
  echo "Do you want to change(Y to change, C to conntinue)?"
  read ans
  if [ $ans = C ] || [ $ans = c ]; then
  /// .... finish the loop
  elif [ $ans = y ] || [ $ans = Y ]; then
  /// .... continue while loop
  else
  echo "Wrong selection."
  /// .... continue while loop
  fi
exit 0

我将其更改为以下内容,但现在它陷入了无限循环:

echo "Enter id:"
read line
echo "Your id: $line"
echo "Do you want to change(Y to change, C to conntinue)?"
read ans
while [ $ans = y ] || [ $ans = Y ];:
do
  echo "Enter id:"
  read line
  echo "Your id: $line"
  echo "Do you want to change(Y to change, C to conntinue)?"
  read ans
done

答案1

问题出在这行:

while [ $ans = y ] || [ $ans = Y ];:

应该是

while [ $ans = y ] || [ $ans = Y ];

问题在于冒号是 bash 内置的,被解释为true。更多信息请访问GNU Bash Builtin 中的 `:'(冒号)的用途是什么?

以下代码对我有用

#!/bin/env bash
echo "Enter id:"
read line
echo "Your id: $line"
echo "Do you want to change(Y to change, C to conntinue)?"
read ans
while [ $ans == y ] || [ $ans == Y ] ;
do
echo "ANS: ${ans}"
  echo "Enter id:"
  read line
  echo "Your id: $line"
  echo "Do you want to change(Y to change, C to conntinue)?"
  read ans
done

注意:最好包含舍邦在脚本的顶部。

相关内容