while/do/done
The usage of while is similar to that of C language. For example, a script to verify passwords:
#! /bin/sh echo "Enter password:" read TRY while [ "$TRY" != "secret" ]; do echo "Sorry, try again" read TRY done
The following example controls the number of loops through arithmetic operations:
#! /bin/sh COUNTER=1 while [ "$COUNTER" -lt 10 ]; do echo "Here we go again" COUNTER=$(($COUNTER+1)) done
break和continue
break[n] can specify several layers of loops to jump out of; continue skips this loop, but will not jump out of the loop.
That is, break to jump out, continue to skip.
Exercise: Modify the program for verifying the password above. If the user enters the wrong password five times, it will report an error and exit.
#! /bin/bash count=4 echo "input a passwd" read psd while [ "$psd" != "tw123" ]; do count=$[count-1] printf "Enter again\n" read psd if [ "$psd" == "tw123" ]; then printf "success.\n" break; elif [ $count -le 0 ];then printf "break\n" break be done