Shell Basics (iii): Using a For loop structure, using the while loop structure, scripting based on case branching, using shell functions, interrupts, and exits

Source: Internet
Author: User
Tags chmod define function stdin

First, using the For loop structure

Target:

This case requires writing a shell script chkhosts.sh that uses a for loop to detect the surviving status of multiple hosts, with the following requirements and instructions:

1> Ping Detection of 192.168.4.0/24 network segments
2> Ping Detection can refer to the pinghost.sh script of the preceding day
The 3> script can traverse the ping hosts and feed back the surviving status

After the test script is executed, the feedback results are as shown.

Solution:

In a shell scripting application, a common for loop takes a traversed, list-based execution process that iterates through a list of values by specifying a variable and performs a fixed set of actions after each copy.

The syntax structure for the For loop is as follows:

For variable name in value list
Do
Command sequence
Done

steps:

Step One: Practice for loop basic usage

Script 1, create accounts in bulk by looping through the account file User.txt:

[Email protected] ~]# vim for01.sh
#!/bin/bash
For I in $ (cat root/user.txt)
Do
Useradd $i
echo "123456" | passwd--stdin $i
Done
[Email protected] ~]# chmod +x for01.sh

Step two: Batch detection of the survival status of multiple hosts

1) Write the following script:

[Email protected] ~]# vim chkhosts.sh
#!/bin/bash
For IP in {1..254}
Do
Ping-c 3-i 0.2-w 3 192.168.4. $IP &>/dev/null
If [$?-eq 0]; Then
echo "Host 192.168.4. $IP is up."
Else
echo "Host 192.168.4. $IP is down."
Fi
Done
[Email protected] ~]# chmod +x chkhosts.sh

2) testing, validating scripts

[Email protected] ~]# vim chkhosts.sh
... ...
[Email protected] ~]#./chkhosts.sh
Host 192.168.4.5 is up.
Host 192.168.4.6 is down
... ...

Second, using the while loop structure

Target:

This case requires writing three scripts that use a while loop to achieve the following objectives:

1> Batch Add user account: Stu1-stu20
2> Bulk Delete user account: Stu1-stu20
3> detecting 192.168.4.0/24 network segments, listing host addresses not in line

Solution:

The while loop is a conditional execution process that repeatedly determines the specified test condition, as long as the condition is performed immediately with a fixed set of operations until the condition changes to a non-established one. So the condition of the while loop is usually controlled by a variable, which changes the value of the variable in the loop body so that it exits at the appropriate time and avoids getting into a dead loop.

The syntax structure of the while loop is as follows:

While condition test
Do
Command sequence
Done

steps:

Step One: Batch Add user account Stu1-stu20

Added account has a fixed prefix stu (can be set in practice), multiple accounts starting from 1 numbers, such as STU1, STU2, Stu3 、......、 stu20. --Write script uaddwhile.sh, realize the function of adding these 20 user accounts in bulk, the password is set to 123456.

The scripting reference is as follows:

    [[email protected] ~]# vim uaddwhile.sh
    #!/bin/bash
     prefix= "Stu"                                        //define user name prefix
    i=1
    while [$i-le]
     do
        useradd ${prefix} $i                                //Added Username: prefix + number
        echo "123456" | passwd--stdin ${prefix} $i &>/dev/null
        let i++
     Done
    [[email protected] ~]# chmod +x uaddwhile.sh

Execute the script and verify the results:

[Email protected] ~]# vim uaddwhile.sh
[Email protected] ~]#./uaddwhile.sh
[[email protected] ~]# grep ^stu/etc/passwd//Check for added users
Stu1:x:531:531::/home/stu1:/bin/bash
Stu2:x:532:532::/home/stu2:/bin/bash
Stu3:x:533:533::/home/stu3:/bin/bash
Stu4:x:534:534::/home/stu4:/bin/bash
Stu5:x:535:535::/home/stu5:/bin/bash
... ...

Step Two: Delete user accounts in bulk Stu1-stu20

Create a script udelwhile.sh to delete these accounts in bulk for the user accounts that were previously executed in bulk by the uaddwhile.sh script. Structure, as long as it is replaced by delete-related actions.

The scripting reference is as follows:

[Email protected] ~]# vim udelwhile.sh
#!/bin/bash
prefix= "Stu"
I=1
While [$i-le 20]
Do
Userdel-r ${prefix} $i &>/dev/null
Let i++
Done
[Email protected] ~]# chmod +x udelwhile.sh

Execute the script and verify the results:

[Email protected] ~]#./udelwhile.sh
[[email protected] ~]# grep ^stu/etc/passwd//re-check no corresponding account information
[Email protected] ~]#

Step three: Detect 192.168.4.0/24 network segment, list the host address not the line

1) Task demand and thinking analysis

The requirement is "detect 192.168.4.0/24 network segment, list host address not in line".

The detection target is a network segment whose network part is "192.168.4." Can be used as a fixed prefix, while the host part includes successive addresses from 1~254, so it can be controlled by combining while loops and self-increment variables.

2) write scripts based on implementation ideas

[Email protected] ~]# vim chknet.sh
#!/bin/bash
Net= "192.168.4."
I=1
While [$i-le 254]
Do
Ip= "${net} $i"
Ping-c 3-i 0.2-w 1 $IP &>/dev/null
If [$?-eq 0]; Then
echo "Host $IP is up."
Else
echo "Host $IP is down."
Fi
Let i++
Done
[Email protected] ~]# chmod +x chknet.sh

3) testing, validating scripts

[Email protected] ~]#./chknet.sh
Host 192.168.4.1 is down.
Host 192.168.4.2 is down.
Host 192.168.4.3 is down.
Host 192.168.4.4 is down.
Host 192.168.4.5 is up.
.. ..
Host 192.168.4.250 is down.
Host 192.168.4.251 is down.
Host 192.168.4.252 is down.
Host 192.168.4.253 is down.
Host 192.168.4.254 is down.

Iii. writing scripts based on case branching

Target:

This case requires writing a test.sh script with the following requirements:

1> can use Redhat, Fedora control parameters
2> control parameters pass through positional variables
3> when the user enters the Redhat parameter, the script returns to Fedora
4> when the user enters the fedora parameter, the script returns Redhat
5> when the user enters additional parameters, an error message is prompted

Solution:

The case branch is a method of matching execution, which pre-sets a possible value for the specified variable, determines whether the actual value of the variable matches a preset value, performs a corresponding set of actions if there is a match, and performs a pre-set default action if no value matches.

The syntax structure of the case branch is as follows:

Case Variable value in
Mode 1)
command sequence 1;;
Mode 2)
command sequence 2;;
.. ..
*)
Default command sequence
Esac

steps:

Step one: Write the script file

The scripting reference is as follows:

[Email protected] ~]# vim test.sh
#!/bin/bash
Case $ in
Redhat
echo "Fedora";;
Fedora
echo "Redhat";;
*)//Default Output script usage
echo "Usage: $ {Redhat|fedora}"
Exit 1
Esac
[Email protected] ~]# chmod +x test.sh

Step two: Verify, test script

The correct usage is prompted when no parameters are supplied, or if the supplied parameter is not recognized:

[Email protected] ~]#./test.sh
Usage:./test.sh {Redhat|fedora}

To confirm the response Redhat control parameters:

[Email protected] ~]#/test.sh Redhat
Fedora

Confirm that the Fedora control parameters can be responded to:

[Email protected] ~]#./test.sh Fedora
Redhat

Iv. using shell functions, interrupts, and exits

Target:

This case requires the writing of two shell scripts with the following requirements:

? A funexpr.sh script: 2 integer numeric parameters are provided by the user at execution time to calculate the addition, subtraction, multiplication, and removal results of these 2 integers

Solution:

In a shell script, some of the actions that need to be reused are defined as public statement blocks, which can be called functions. By using a function, you can make the script code more concise, enhance legibility, and improve the execution efficiency of the shell script.

1) How to define a function

Format 1:

Function name {
Command sequence
.. ..
}

Format 2:

Function name () {
Command sequence
.. ..
}

2) Call to function

Called directly using the function name, if the function can handle positional arguments, you can use the function name parameter 1, parameter 2: ..” In the form of a call.

NOTE: The definition statement for the function must appear before the call, otherwise it cannot be executed.

3) Test Syntax format

[[email protected] ~]# MYCD () {//define function
> Mkdir/test
> Cd/test
>}
[[email protected] ~]# MYCD//Call function
[[email protected] ~]# MYCD () {//define function
> mkdir $
> CD $
>}
[[email protected] ~]# MYCD/ABC//Call function
[[email protected] ~]# mycd/360//Call function

steps:

Step one: Write the funexpr.sh script

1) Task demand and thinking analysis

The user provides 2 integer arguments at execution time, which can be read in by the location variable, $.

For a given two integers, arithmetic can be treated as a set of actions, which can be defined as a function, which in turn is responsible for the subtraction operation and outputting the result.

When you call a function, pass the user-supplied two arguments to the function handler.

2) Write a script file according to the implementation idea

[Email protected] ~]# vim funexpr.sh
#!/bin/bash
Myexpr () {
echo "$ + $ = $[$1+$2]"
echo "$-$ = $[$1-$2]"
echo "$ * $ = $[$1*$2]"
echo "$/$ = $[$1/$2]"
}
MYEXPR $
[Email protected] ~]# chmod +x funexpr.sh

3) test script execution effect

[Email protected] ~]#./funexpr.sh 43 21
43 + 21 = 64
43-21 = 22
43 * 21 = 903
43/21 = 2
[Email protected] ~]#./funexpr.sh 1234 567
1234 + 567 = 1801
1234-567 = 667
1234 * 567 = 699678
1234/567 = 2

V. Interruption and withdrawal

Target:

This case requires the writing of two shell scripts with the following requirements:

1> from the keyboard loop takes an integer (0 end) and sums it, outputting the final result
2> skips a multiple of 1~20 within 6, outputs the square value of the other number, and sets the exit code to 2

Solution:

Interrupts and exits are implemented in shell scripts through break, continue, and exit.

Break can end the entire loop; continue ends the loop and goes to the next loop; exit ends the entire script, with the following case:

[Email protected] ~]# cat/root/test.sh
#!/bin/bash
For i in {1..5}
Do
If [$i-eq 3];then
Break #这里将break替换为continue, exit test script execution effect separately
Fi
Echo $i
Done
Echo Program End

steps:

Step One: Scripting sum.sh

1) Writing script files

[Email protected] ~]# vim sum.sh
#!/bin/bash
While read-p "Please enter an integer to be accumulated (0 means end):" X
Do
[$x-eq 0] && break
SUM=$[SUM+X]
Done
echo "sum is: $SUM"
[Email protected] ~]# chmod +x chkint.sh

Step two: Write the sum.sh script file

1) Writing script files

[Email protected] ~]# vim mysum.sh
#!/bin/bash
I=0
While [$i-le 20]
Do
Let i++
[$[i%6]-ne 0] && continue
Echo $[i*i]
Done
Exit 2
[Email protected] ~]# chmod +x sum.sh

Shell Basics (iii): Using a For loop structure, using the while loop structure, scripting based on case branching, using shell functions, interrupts, and exits

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.