1. The script determines whether the command output is empty
(1) Determine if the string is empty
If ["$str" = ""]
If [x "$str" = x]
If [-Z ' $str '] (-n is not null)
Note: You have to double quotation marks, or some commands will be error, form a good habit!
2. Enter y/n
You can use the judgment symbol for data judgment, such as checking if a variable is empty [-Z $SHELL], and note that the components within the brackets ("[]") must be separated by a space. The following script is available:
#!/bin/bashread-p "Input You Choice (y/n):" choice["$choice" = = "Y"] | | ["$choice" = = "Y"] && echo "Ok,continue" && exit 0["$choice" = = "n"] | | ["$choice" = = "N"] && echo "oh,interrupt!" && exit 0echo "I don ' t know what's your choice" && E XIT 0
#! /bin/shecho "Is it morning? Please answer yes or No. " Read Yes_or_noif ["$YES _or_no" = "YES"]; Then echo "Good morning!" elif ["$YES _or_no" = "NO"]; Then echo "Good afternoon!" else echo "Sorry, $YES _or_no not recognized. Enter yes or No. " Exit 1fiexit 0
(3) While condition loop
Similar to the C language. Like a script that validates the password: #! /bin/shecho "Enter password:" Read trywhile ["$TRY"! = "secret"]; Do echo "Sorry, try again" Read Trydone The following example controls the number of cycles by arithmetic operations: #!/bin/shcounter=1while ["$COUNTER"-lt]; do echo "Here's Go Again" counter=$ (($COUNTER + 1)) done
(3) Case and while combination
#!/bin/bashwhile: : True, always loop do the command to loop execution echo-n "Enter any number [1-5]:" Enter the ordinal 1-5 read Nu Set the read variable case $nu in to select, enter if 1-5 of the number 1|2|3|4|5) echo "Enter Anumber 1 and 5" on the loop this line, let you keep the input 1-5 ;; *) If you enter a number that is not 1-5 echo-n "wrong numbers, continue (y/n?:)" Ask if you continue read con setting read variable case $con in make a selection to see if it is y|yes| y| Yes these few y|yes| y| Yes) continue If yes, then skip and let you re-enter, if not ; *) then execute this break exit loop break ;; Esac Esacdone
Shell Scripting Practices