如何在 Bash 中循环 if 条件?

如何在 Bash 中循环 if 条件?

我想知道要设置什么条件才能再次启动 if,所以我希望我的程序循环直到答案为否:

function createFile {
  echo "Enter file name"
  read -r file
  mkdir /home/jeremy/MesFichiers/$file
  echo -n "do you want to create another file (y/n)?"
  read -r answer
  if [ "$answer" != "$answer#[Yy]]}" ];
    echo "enter file name"
    read -r file
    mkdir /home/jeremy/MesFichiers/$file
  # (conditions to restart the if)
  else
    echo "Thanks"
  fi
}

答案1

我建议使用while 循环,与有条件中断前任。

#!/bin/bash

while :
do
  read -r -p "Enter file name: " file
  mkdir "/home/jeremy/MesFichiers/$file"

  read -r -p "do you want to create another file (y/n)? " answer
  case $answer in
    [Yy]*)
      continue
    ;;
    *)
      echo "Thanks"
      break
    ;;
  esac
done

请注意,如果您决定使用if ... then构造代替语句case,则测试运算符的语法对于空格非常具体,即if [ string1 = string2 ]

答案2

这是另一个版本,功能与steeldriver 的回答使用条件 while 循环。这可以使代码更短:

#!/bin/bash

while [[ ${answer:=y} = [Yy] ]]          # sets default to y. [Yy] accepts both Y or y
do
  read -r -p "Enter file name: " file  
  mkdir "/home/jeremy/MesFichiers/$file"
  read -r -p "do you want to create another file (y/n)? " answer
done

希望这可以帮助

答案3

您还可以利用trap它拦截 shell 信号。read在子 shell 内部启动可确保trap执行循环内的代码,而不是脚本本身的代码。

#!/bin/bash

trap \
'printf \\n%s\\n "ctrl + c ..."; break' SIGINT

a=${1:-$HOME/MesFichiers}
while :; do
    ( \
        read -r -p \
        "Create a directory in '$a' (ctrl + c to abort): " && mkdir "$a/$REPLY" \
    )
done

trap - SIGINT # Reset specified signal.

echo "Rest of the code!"

相关内容