Loop (?) If statement

I am a noob for shell scripts and I am wondering:

#!/usr/local/bin/bash number=5 echo "Enter 'yes' to continue, 'no' to abort:" read choice if [ $choice = yes ]; then while [ $number -lt 10 ]; do echo "The script is now looping!" done elif [ $choice = no ]; then echo "Loop aborted" else echo "Please say 'yes' or 'no'" read choice # What now? fi 

What should I do if the if statement double-checks your choice of $ (on line 13), if you don't say yes or no?

Thanks.

+4
source share
2 answers
  • You can put the code from "echo Enter ..." to fi in the outer while loop. The while loop will cycle until $ choice is yes or no. Remove the last else clause by doing this (it will be redundant).

  • PS

    . you need to increase (or change) the number of $ in your inner loop. Otherwise, it will work endlessly.

+2
source

You can track whether to quote a variable named invalid_choice

 invalid_choice=true while $invalid_choice; do read choice if [ "$choice" = "yes" ]; then invalid_choice=false ... elif [ "$choice" = "no" ]; then invalid_choice=false ... else echo "Please say yes or no" done 

Or you could generalize it to a function if you need to do this a lot:

 function confirm() { local ACTION="$1" read -p "$ACTION (y/n)? " -n 1 -r -t 10 REPLY echo "" case "$REPLY" in y|Y ) return 0 ;; * ) return 1 ;; esac } confirm "Do something dangerous" || exit 
+2
source

Source: https://habr.com/ru/post/1446721/


All Articles