Shell condition-loop-branch-function

Source: Internet
Author: User
Tags terminates

Shell Process Control (if structure loop structure branch structure)
Controlling the execution of scripts
Process control can be nested with each other, or they can nest themselves
Judging result execution according to condition condition
-----------------------------------------------------
If structure

Single Branch

if condition judgment; then
Code to execute
......
Fi

If condition judgment
Then
Code to execute
......
Fi
----------------------------------------
Dual Branch

if condition judgment; then
Code
......
Else
Code
......
Fi
--------------------------------------------------------------------
#!/bin/bash
Read-p "Please enter the user name you are looking for" username
Echo $username

If [-N "$username"];then
ID $username &>/dev/null
If [$?-eq 0];then
echo "User already exists"
Else
#usd $username
Useradd $username
echo $username | passwd--stdin $username &>/dev/null
Fi
Else
echo "You have to enter the user name to check"
Fi
----------------------------------------
Multi-Branch
If condition judgment 1;then
Code
.......
Elif Condition Judgment 2;then
Code
.......

Elif Condition Judgment N;then
Code
.......
Else
Code that executes when all of the above criteria are not established
Fi
______________________________________________________________________

[-e/media/cdrom] | | Mkdir/media/cdrom

----------------------------------------------------------------------
Vim ping.sh
#!/bin/bash
If [-N "$"];then
Ping-c 3 $ &>/dev/null
If [$? -eq 0];then
echo "Host Online"
Else
echo "Host is not online"
Fi
Else
echo "Executes the script in the following format:"
echo "$ IP Address"
Fi
: Wq

chmod +x ping.sh
./ping.sh 1.1.1.1

----------------------------------------------------------------------
Judging grades based on the input score
86~100 Good
85-71 Excellent
70-61 Good
60 points Pass
Less than 60 retake
Less than 50 points repeat

Questions to consider:
What if I don't enter a score?

Score range can only be 1-100 between the loss of results, the access to exceed the score?

What do I do if I enter a letter that is not a score?
----------------------------------------------------------------------
Loop structure (code that needs to be executed repeatedly in the script, executed in the loop structure)
Add 100 system users
Check for hosts that are not online in the network segment 192.168.1.0/24
$name

For loop structure (traverse data)

For variable name in value list
Do
Loop body
Done

For x in Jim, Lucy A
Do
echo "PLJ"
Done

Build Tools Seq 15
Seq 11 37
Seq 10 2 28

{1..100}
{A.. Z
--------------------------------------------------------------------
Executing the script is to check the running status of the 4 servers in the current system in turn
httpd Crond Network ATD
If the service does not run the startup service, the display service is running if the service is running.


For Sername in httpd crond network ATD
Do
Service $sername Status

read -p   "Please enter your score   "    x
if   [  $x  -lt   60    ]; then
       echo  "Retake"
elif   [   $x   -eq   60  ];then
       echo  "Pass"
elif  [$x   -gt   60   -a   $x  -le   70 & nbsp ];then
       echo  "good"
elif  [$x   -ge   71    -a   $x  -le   85  ];then
        echo  "excellent"
elif  [$x   -ge   86   -a   $x  -le& nbsp;  100  ];then
       echo  "good"
Else
        echo  "The effective range of results is 1~100"
Fi

----------------------------------------------------------------------
Loop structure
C-FOR structure

> >= < <=

for (initialization; condition judgment; step))
Do
Loop body
Done


For ((x=1;x<=5;x++))
Do
Echo $x
Done

----------------------------------------------------------------------
While loop structure


While condition judgment
Do
Loop body
Done
---------------------------------------------------
#/bin/bash
#正序输出数字1-5
I=1
While [$i-le 5]
Do
Echo-n "$i"
Let i++
Done
Echo
-----------------------------------------------------
#!/bin/bash
#倒序输出数字1-5
I=5
While [$i-ge 1]
Do
Echo-n "$i"
#i = ' expr $i-1 '
Let i--
Done
Echo
--------------------------------------------------------
Until cycle structure (conditional judgment is not immediately executed loop body)

Until condition judgment
Do
Loop body
Done

Positive sequence output number 1-5 using until loop structure

1 2 3 4 5 positive sequence


5 4 3 2 1 Reverse
I=5
Until [$i-lt 1]
Do
Echo $i
Let i--
Done
---------------------------------------------------------------------
In script four.sh, use for c-for while until loop structure reverse output number 1-5

Echo--------------for-----------
For I in 5 4 3 2 1
Do
Echo-n "$i"
Done
Echo
Echo $i

Echo---------------c-for-------------
for   ((i=5;i>=1;i--))
do
          echo -n    $i  
Done
Echo
Echo $i
echo ------ ------------while----------------
i=5
while  [  $i   -ge   1 ]
do
      echo -n  "  $i  "
     let  i--
Done
Echo
Echo $i
echo -------------------until--------------------
i=5
until  [  $ i  -lt   1  ]
do
     echo -n  "  $i  "
     let  i--
Done
Echo

----------------------------------------------------------------------
case  Branch Structure    Perform different actions depending on the value of the variable
                            case is usually used with shell functions to write a start    for the source service                           script.

case   $ variable name   in
"value 1")
          code
          ...
         ;;
Value 2)
          code
           ...
         ;;
"Value n")
          code
           ...
         ;;
*)
     Code
          ......    
Esac
----------------------------------------------
Process Control function   

Execution of a cyclic structure
Break terminates execution of the current loop structure
Continue terminates this loop of the current loop structure and begins execution of the next loop

Return value returned to function

Exit terminates execution of script
The default return value is 0
How to set the return value
Exit 3

x=10
Exit $x

Ping-c 3 1.1.1.1 &>/dev/null
Exit $?

Shift Displacement function
Move the position variable of the script or function to one bit, and delete the position variable with no value

Calculates the sum of any number of sums
#!/bin/bash
Sum=$1
Shift

While [$#-GT 0]
Do
sum= ' expr $sum + $ '
#let sum=sum+$1
Shift
Done
Echo $sum
: Wq

Controlling the execution of scripts

(Controls the process of Process Control execution)

----------------------------------------------------------------
Custom Shell functions

What is a function? The code that implements a certain function in the script, encapsulates, defines a name.

Why use a function? Simplify operations

How do I define a function?
Function name {
function body
......

Function name () {
function body
......

How do I invoke a function?
Name of function

What are the function usage rules?
The call is defined first, but the value definition does not call the
Function name distinguishes letter case
Function name in the same time, after the definition of the effective

Variables defined in the function body are local variables that can only be used within the function body.
Variables defined in the body of a function are global variables and can be used by all functions.

Passing values to a function by positional arguments when calling a function
#!/bin/bash
Sayme () {
echo "Hello A $"
}
Sayme PLJ
Sayme Bob
Sayme Lucy


Functions can be called to each other or recursively (call yourself)

PriA () {
Read-p "Please input num" x
If [-Z ' $x '];then
PriA
Else
Echo $x
Fi
}

.  (){  .   |  .   &}; .

Delete a function? Name of unset function
-----------------------------------------------------------------
Vim fun.sh
#!/bin/bash
Cha () {
If [$#-eq 2];then
x= ' expr $-$ '
echo "$-$ = $x"
Else
echo "Cha num2 num2"
Fi
}

Sum2 () {
 if [$#-eq 2];then
  sum= ' expr $ + $ '
  echo "+  $ = $sum"
 else< br>    echo "sum2  num1  num2"
 fi
}
Read-p "Please select the type of operation   + | -"   lx
Case" $LX "in
" + ")
     sum2 $*
    ;;
"-")
     cha  $*
    ;;
*)
   echo "operation type {  + | -} "
Esac
: Wq
---------------------------------------------------------------------
Apply case  +   Shell functions   Writing startup scripts to the source service
                                                httpd
----------- ------------------------------------------------------

----------------------------------------------------------------------
Jsq.sh calculates the result of any number +-*/operation, which can be computed according to the type of operation.

#!/bin/bash
Sum () {
Sum=$1
Shift
While [$#-GT 0]
Do
sum= ' expr $sum + $ '
Shift
Done
Echo $sum
}

Cha () {
Sum=$1
Shift
While [$#-GT 0]
Do
sum= ' expr $sum-$ '
Shift
Done
Echo $sum
}
Read-p "Please select the type of Operation + | -"LX
Case ' $LX ' in
"+")
Sum $*
;;
"-")
Cha $*
;;
*)
echo "operation type {+ | - }"
Esac

Shell condition-loop-branch-function

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.