Linux shell basic programming 2, linuxshell BASIC Programming
While Loop
Syntax 1:
While [condition]
Do
Command Sequence
Done
Syntax 2:
While read-r line
Do
Command Sequence
Done
(Remember that while and left brackets must have spaces)
Example
1 #!/bin/bash2 j=13 SUM=04 while [ $j -lt 10 ]5 do6 SUM=$((SUM+j))7 j=$[j+1]8 done9 echo $SUM
If judgment statement
Syntax 1:
If condition
Then
Command Sequence
Fi
Syntax 2:
If condition
Then
Conditional Sequence
Else
Conditional Sequence
Fi
Syntax 3:
If condition
Then
Conditional Sequence
Elif Condition
Then
Conditional Sequence
Elif Condition
Then
Conditional Sequence
Else
Conditional Sequence
Fi
Example
#!/bin/bashif [ -d /tmp/123 ];thenecho "this is directory"else echo "this is not directory"fi
Case statement
Syntax 1:
Case $ variable name in
Condition 1)
Command Sequence
;;
Condition 2)
Command Sequence
;;
Condition 3)
Command Sequence
;;
*)
Command Sequence
Esac
Syntax 2:
Case $ variable name in
Condition 1 | Condition 4)
Command Sequence
;;
Condition 2 | condition 5)
Command Sequence
;;
Condition 3 | Condition 6)
Command Sequence
;;
*)
Command Sequence
Esac
1 #!/bin/bash 2 case $1 in 3 top) 4 top 5 ;; 6 free) 7 free 8 ;; 9 df)10 df11 ;;12 *)13 echo "no param"14 esac
View Code
Function Definition:
Syntax 1:
Method Name (){
Command Sequence
}
Syntax 2:
Function Method Name {
Command Sequence
}
1 #!/bin/bash2 sum(){3 echo $(($1+$2))4 }5 sum 5 6