Process Control statements in shell programming

Source: Internet
Author: User
Tags case statement glob


1. Conditional selection: If statement

① Single Branch

if judgment condition; then condition is true Branch code FI

② Dual Branch

if judgment condition; Then condition for true Branch code else condition for false Branch code FI

③ Multi-Branch

if judgment condition 1; Then condition is true branch code elif judging condition 2; Then condition is true branch code elif judging Condition 3; Then condition is true branch code else above condition is false Branch code FI

Example: Please user input score: 80-100 for excellent, 60-79 for pass, other elimination.

#!/bin/bash read-p "Pelease input your score:" Score if ["$score"-ge 80-a "$score"-le];then echo "excellent" Eli f ["$score"-lt 80-a "$score"-ge];then echo "eliminated" through "else echo" fi

2. Condition Judgment: Case statement

Syntax: Case variable reference in PAT1) branch 1;;    PAT2) branch 2;;        .. *) default branch;; Esac

Case supports GLOB-style wildcard characters:
*: Any character of any length
?: any single character
[]: Any single character within the specified range
A|b:a or B

。。。

Example: Write a script that prompts the user to enter Yes or no case-insensitive and to determine whether the user is entering yes or no or other information.

#!/bin/bashread-p "Please input yes or no:" ynans=$ (Echo $yn |tr "[[: Upper:]]" "[[: Lower:]]") case $ans Iny|yes) echo y es;; N|no) echo no;; *) echo Yes/no?esac

3. For loop

Syntax: for variable name in list; Do
Loop body
Done

Execution mechanism: Assigns the element in the list to the "variable name" in turn; The loop body is executed once each assignment; The loop ends until the elements in the list are exhausted.

List Generation Method:
(1) Give the list directly
(2) List of integers:
(a) {start: End
(b) $ (SEQ [start [step]] end)
(3) command to return a list
$ (COMMAND)
(4) using glob, such as: *.sh
(5) variable reference;
[email protected], $*

Example: Print a 99 multiplication table with a for loop.

#!/bin/bashfor i in {1..9};d O to J in $ (seq $i);d o echo-ne "$j * $i =$[$i * $j]\t" Done Echodone

Special format for loop:

For (control variable initialization; conditional judgment expression; control variable correction expression))
Do
Loop body
Done

    • Control variable initialization: Executes only once when running to a loop code snippet

    • Correction expressions for control variables: The control variable correction operation is performed at the end of each cycle, then the condition is judged.

      Example: Print a 99 multiplication table with a for loop special format.

#!/bin/bashfor ((i=1;i<=9;i++)); Do for ((j=1;j<=i;j++)); Do echo-ne ' $j * $i =$[$j * $i]\t "Done Echodone

4. While loop

Syntax: while CONDITION; Do
Loop body
Done

CONDITION: cyclic control conditions; Before entering the cycle, make a judgment; once each loop is judged again; the condition is "true", then a loop is executed until the condition test state is "false" to terminate the loop
Therefore: Condtion generally should have a cyclic control variable, and the value of this variable will be continuously corrected in the loop body
Enter condition: Condition is true
Exit Condition: Condition is false

Example: Sum of numbers within 100 that can be divisible by 3

#!/bin/bashdeclare i=1declare sum=0while ["$i"-lt];d o let i++ if [$[i%3]-ne 0];then continue fi let sum+= $idoneecho sum is $sum

A special use of the while (traversing each line of the file):

while read line; Do
Loop body
Done </path/from/somefile
Read each line in the/path/from/somefile file sequentially and assign the row to the variable line.

Example: Find all users with an even ID number and display their user name and ID number.

While read line;d o if [$[' echo $line |cut-d:-f3 '%2]-eq 0];then echo-ne "username: ' echo $line |cut -d:-f1 ' \ t ' echo ' UID: ' echo $line |cut-d:-f3 ' "fi done</etc/passwd

or pass the content over the pipe to the while loop:

Example: Notifies the user if the disk utilization is greater than 80%.

#!/bin/bashdf|grep "/DEV/SD" |while read disk;d o diskused=$ (echo $disk |sed-r ' s/.* ([0-9]+)%.*/\1/') diskname=$      (Echo $disk |cut-d ""-f1) [$diskused-ge] && Echo ' $diskname'll bi full: $diskused% ' done


5. Untill cycle

grammar until CONDITION; Do
Loop body

Done
Entry condition: CONDITION is False
Exit Condition: CONDITION is True

Example: printing a 99 multiplication table with until

#!/bin/bashj=1i=1until ["$j"-gt 9];d o until ["$i"-GT "$j"];d o echo-ne "$i * $j =$[i*j]\t" let i++ Do echo let I=1 let J++done

6. Circular Control Statement continue

Continue used in the loop body
Continue [n]: End of the nth layer of the current cycle, and directly into the next round of judgment; the inner layer is the 1th floor.
While CONDTIITON1; Do
CMD1
...
if CONDITION2; Then
Continue
Fi
Cmdn
...
Done

Example: Print a number other than 5 1-10.

#!/bin/bashfor i in {1..10};d o    if [  $i  -eq 5 ]; then        continue    else         echo  $i     fi                                                                                                                                                         done

7. Loop Control Statement Break

Grammar:

Break [n]: Early end of the nth layer cycle, the inner layer is the 1th layer while CONDTIITON1; Do CMD1 ... if CONDITION2; Then break fi cmdn ... done

The difference between break and continue is that continue skips a single loop that satisfies a condition in a loop, and break jumps out of its own loop body by default. In the continue example, if you change to break, only 1-4 is printed, because the 5 trigger breaks out of the loop after it is not printed.

8. Loop Control Shift Command

Shift [N]
n is used to move the list of parameters to the left for a specified number of times, with the default shift left once.
Parameter list once moved, the left-most argument is removed from the list. The while loop iterates through the position parameter list, often to shift.
Example

#!/bin/bashwhile (($#>0));d o echo $* shiftdone display results: [[email protected] app]#./haha.sh a b c d ea b c D EB c D EC D Ed EE

9. Select Cycle and Menu

Select variable in listdo loop body command done
    • The Select loop is used primarily to create menus, and menu items in numerical order are displayed on standard errors, and a PS3 prompt is displayed waiting for user input.

    • The user enters a number in the menu list and executes the corresponding command.

    • User input is saved in the built-in variable REPLY

    • Select is an infinite loop, so remember to exit the loop with the break command, or terminate the script with the Exit command. You can also press CTRL + C to exit the loop.

    • Select is often used in conjunction with case

    • Similar to a For loop, you can omit the in list and use positional parameters at this time

      Example

#!/bin/bashps3= "please choose your menu: " select menu in huimian  lamian hulatang yrt;do      case  $REPLY  in                                                                                                                                                  1)           echo  "The price  is \$10 "   ;; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;2)           echo  " the price is \$15 "   ;; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;3)           echo  " The price is \$5 "    ;; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;4)           echo  " the price is \$20 "   ;;       *)           echo  " Get out! "           break      esacdone

10. Signal Capture Trap

Trap ' trigger command ' signal
When a custom process receives a specified signal from the system, it executes the triggering instruction without performing the original operation
Trap ' signal
Operations that ignore signals
Trap '-' signal
Operation to restore the original signal
Trap-p
column-defined signal operation

Example:

#!/bin/bash trap ' echo ' signal:sigint "' int trap-p for ((i=0;i<=10;i++)) does sleep 1 echo $i done trap ' int trap-p fo R ((i=11;i<=20;i++)) do sleep 1 echo $i doing trap '-' int trap-p for ((i=21;i<=30;i++)) does sleep 1 echo $i done

Process Control statements in shell programming

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.