Review shell scripts

Source: Internet
Author: User
Tags iptables

What is a shell script. First, it is a script and cannot be used as a formal programming language. Because it's running in the shell of Linux, it's called a shell script. To be blunt, a shell script is a collection of commands. For example, I want to do this:

1) enter into the/tmp/directory;

2) List all filenames in the current directory;

3) Copy all current files to the/root/directory;

4) Delete all files in the current directory.

A simple 4 step in the shell window requires you to knock 4 commands, press 4 times to enter. Isn't that a lot of trouble? Of course, this 4-step operation is very simple, if it is more complex command setup requires dozens of operations? In that case it would be troublesome to knock on the keyboard once. So it's a matter of recording all the operations into a document and then calling the commands in the document so that one step can be done. In fact, this document is a shell script, but this shell script has its special format.

The shell script can help us to manage the server very conveniently, because we can specify a task schedule to execute a shell script to implement the requirements we want. This is a very proud thing for Linux system administrators. Now the 139 mailbox is very good, e-mail can also send an e-mail message to the user, using this, we can deploy the monitoring shell script on our Linux server, such as network card traffic is abnormal or the server Web server stopped can send a message to the administrator, At the same time sent to the administrator an alarm SMS so that we can know in a timely manner the server problem.

Give you a piece of advice before you formally write your shell script: Any custom script recommendations are put into the/usr/local/sbin/directory, so that you can manage your documents better, and then your administrator will know where the custom scripts are placed and easy to maintain.

Basic structure of shell scripts and how to execute them

Let's write your first shell script below:

[[email protected]r ~]# cd /usr/local/sbin/[[email protected] sbin]# vim first.sh#! /bin/bash## This is my first shell script.## Writen by Aiker 2018-07-22.dateecho "Hello world!"

Shell scripts are usually suffixed with. SH, which is not to say no. sh This script cannot be executed, just a habit of everyone. So, later you find the. sh suffix file then it could be a shell script. The first line in test.sh is to "#! /bin/bash "begins, it means that the file uses the bash syntax. If you do not set the line, your shell script can execute, but this does not conform to the specification. # indicates a comment, as mentioned earlier. Followed by some comments about the script and the author and creation date or version, and so on. Of course, these comments are not necessary, if you are lazy, can be omitted, but not recommended to omit. Because with the gradual transition of working time, you will write more shell scripts, if one day you look back at a script you wrote, it is likely to forget what the script is used to do and when to write. So it is necessary to write the comments. In addition, the system administrator is not only you, if the other administrator to view your script, he can not understand it is very depressed. Here's how to run this script:

[[email protected] sbin]# sh first.sh2018年 07月 22日 星期五 18:58:02 CSTHello world!

In fact, the shell script also has a way to do this:

[[email protected] sbin]# ./first.sh-bash: ./first.sh: 权限不够[[email protected] sbin]# chmod +x first.sh[[email protected] sbin]# ./first.sh2018年 07月 22日 星期五 18:58:51 CSTHello world!

To use this method to run a shell script, if the script itself has execute permissions, you need to give the script an ' x ' permission. In addition, when using the SH command to execute a shell script, it is possible to add the-X option to view the execution of the script, which helps us debug the script where there is a problem:

[[email protected] sbin]# sh -x first.sh+ date2018年 07月 22日 星期五 20:00:11 CST+ echo ‘Hello world!‘Hello world!

There is a command in this example date that has never been introduced before, and this command is used very frequently in shell scripts, and it is necessary to introduce you to its usage.

Command: Date

Give some practical examples to show you how to use it:

[[email protected] sbin]# date +"%Y-%m-%d %H:%M:%S"2018-07-22 19:41:01

The most common uses of date in scripts are:

data +%YPrint the year in four-bit number format

date +%yPrint the year in two-bit number format

date +%mMonth

date +%dDate

date +%HHours

date +%MMinutes

date +%SSeconds

date +%wWeek, if the result shows that 0 indicates Sunday

Sometimes the date in the script is used a day before:

[[email protected] sbin]# date -d "-1 day" +%d23

Or an hour ago:

[[email protected] sbin]# date -d "-1 hour" +%H18

Even 1 minutes ago:

[[email protected] sbin]# date -d "-1 min" +%M50
Variables in shell scripts

Using variables in shell scripts makes our scripts more professional and more like a language, and the role of variables is certainly not for professional purposes. If you write a shell script that is 1000 lines long, and there is a command or path hundreds of times in the script. Suddenly you think the path does not want to change, that would not be changed hundreds of times? You can use the command for bulk substitution, but it's also cumbersome, and the script looks bloated. The role of variables is to solve this problem.

[[email protected] sbin]# cat variable.sh#! /bin/bash## In this script we will use variables.## Writen by Aiker 2018-07-22.d=`date +%H:%M:%S`echo "The script begin at $d."echo "Now we‘ll sleep 2 seconds."sleep 2d1=`date +%H:%M:%S`echo "The script end at $d1."

The use of anti-quotes in the script, do you still remember its role? ' d ' and ' D1 ' appear as variables in the script, and the format of the variable is defined as a 变量名=变量的值 ' $ ' symbol to be used when referencing variables in the script, which is consistent with the custom variables in the shell that were previously spoken. Here's a look at the script execution results:

[[email protected] sbin]# sh variable.shThe script begin at 20:16:57.Now we‘ll sleep 2 seconds.The script end at 20:16:59.

Below we use the shell to calculate two numbers of the and:

[[email protected] sbin]# cat sum.sh#! /bin/bash## For get the sum of tow numbers.## Aiker 2018-07-22.a=1b=2sum=$[$a+$b]echo "$a+$b=$sum"

The mathematical calculation is to be enclosed in [] and to bring a ' $ ' script outside the result:

[[email protected] sbin]# sh sum.sh1+2=3

Shell scripts can also interact with users:

[[email protected] sbin]# cat read.sh#! /bin/bash## Using ‘read‘ in shell script.## Aiker 2018-07-22.read -p "Please input a number: " xread -p "Please input another number: " ysum=$[$x+$y]echo "The sum of the two numbers is: $sum"

The read command is used in such a place to interact with the user, using the user input string as the variable value. The script execution process is as follows:

[[email protected] sbin]# sh read.shPlease input a number: 2Please input another number: 10The sum of the two numbers is: 12

We might as well add the-X option to take a look at this process:

[[email protected] sbin]# sh -x read.sh+ read -p ‘Please input a number: ‘ xPlease input a number: 22+ read -p ‘Please input another number: ‘ yPlease input another number: 13+ sum=35+ echo ‘The sum of the two numbers is: 35‘The sum of the two numbers is: 35

Sometimes we use the /etc/init.d/iptables restart /etc/init.d/iptables file in front of this command is actually a shell script, why can follow a "restart"? Here is a preset variable for the shell script. In fact, shell scripts can be followed by arguments when executed, and can be followed by multiple.

[[email protected] sbin]# cat option.sh#! /bin/bashsum=$[$1+$2]echo "sum=$sum"

The result of the execution is:

[[email protected] sbin]# sh -x option.sh 1 2+ sum=3+ echo sum=3sum=3

In the script, you will not be surprised, where comes the $ and $, this is actually a default shell script variables, where the value is the execution of the input 1, and the value of $ is executed when the input of the $, of course, a shell script preset variable is unlimited, this time you understand it. There is another $ A, but it represents the name of the script itself. You might want to modify the script:

[[email protected] sbin]# cat option.sh#! /bin/bashecho "$1 $2 $0"

Execution Result:

[[email protected] sbin]# sh option.sh  1 21 2 option.sh
Logical judgments in shell scripts

If you have learned C or other languages and believe that you are not unfamiliar with if, in shell scripts we can also use if logic to judge. The basic syntax for if judgment in the shell is:

1) without Else

if Judgment statement; Then
Command
Fi

For example:

[[email protected] sbin]# cat if1.sh#! /bin/bashread -p "Please input your score: " aif (($a<60)); then    echo "You didn‘t pass the exam."fi

In if1.sh (($a <60)) This form, which is a unique format in the shell script, with a small parenthesis or no error, please remember this format. The result of the execution is:

[[email protected] sbin]# sh if1.shPlease input your score: 90[[email protected] sbin]# sh if1.shPlease input your score: 33You didn‘t pass the exam.

2) with Else

if Judgment statement; Then
Command
Else
Command
Fi

For example:

[[email protected] sbin]# cat if2.sh#! /bin/bashread -p "Please input your score: " aif (($a<60)); then     echo "You didn‘t pass the exam."else     echo "Good! You passed the exam."fi

Execution Result:

[[email protected] sbin]# sh if2.shPlease input your score: 80Good! You passed the exam.[[email protected] sbin]# sh if2.shPlease input your score: 25You didn‘t pass the exam.

The only difference from the previous example is that if you enter a number greater than or equal to 60, you will be prompted.

3) with Elif

If Judgment statement one; Then
Command
Elif Judgment Statement two; Then
Command
Else
Command
Fi

For example:

[[email protected] sbin]# cat if3.sh#! /bin/bash read -p "Please input your score: " a if (($a<60)); then         echo "You didn‘t pass the exam." elif (($a>=60)) && (($a<85)); then         echo "Good! You pass the exam." else         echo "very good! Your socre is very high!" fi

&& here means "and", of course, you can use | | means "or" to execute the result as:

[[email protected] sbin]# sh if3.shPlease input your score: 90very good! Your socre is very high![[email protected] sbin]# sh if3.shPlease input your score: 60Good! You pass the exam.

The above is simply a description of the structure of the IF statement. In determining the size of a value in addition to (()) can be used in the form of [] but can not use;, <, = such a symbol, to use-LT (less than),-GT (greater than),-le (less than equals),-ge (greater than or equal),-eq (equals),-ne (not equals). The following is a simple comparison in the form of a command line, no longer write shell scripts.

[[email protected] sbin]# a=10; if [ $a -lt 5 ]; then echo ok; fi[[email protected] sbin]# a=10; if [ $a -gt 5 ]; then echo ok; fiok[[email protected] sbin]# a=10; if [ $a -ge 10 ]; then echo ok; fiok[[email protected] sbin]# a=10; if [ $a -eq 10 ]; then echo ok; fiok[[email protected] sbin]# a=10; if [ $a -ne 10 ]; then echo ok; fi

And look at the If using && | | The situation:

[[email protected] sbin]# a=10; if [ $a -lt 1 ] || [ $a -gt 5 ]; then echo ok; fiok[[email protected] sbin]# a=10; if [ $a -gt 1 ] || [ $a -lt 10 ]; then echo ok; fiok

In a shell script, if is also often judged about the file attributes, such as whether it is a normal file or a directory, to determine if the files have read and write execution rights. There are several options that are commonly used:

-E: Determine if a file or directory exists

-D: Determine if the directory is not present and whether it exists

-F: Determine if the file is normal and exists

-R: Determine if the document has Read permissions

-W: Determine if Write permission is available

-X: Determine if executable

When you use the If judgment, the specific format is:

if [ -e filename ] ; then

Example:

[[email protected] sbin]# if [ -d /home/ ]; then echo ok; fiok[[email protected] sbin]# if [ -f /home/ ]; then echo ok; fi

Because/home/is a non-file directory, "OK" is not displayed.

[[email protected] sbin]# if [ -f /root/test.txt ]; then echo ok; fiok[[email protected] sbin]# if [ -r /root/test.txt ]; then echo ok; fiok[[email protected] sbin]# if [ -w /root/test.txt ]; then echo ok; fiok[[email protected] sbin]# if [ -x /root/test.txt ]; then echo ok; fi[[email protected] sbin]# if [ -e /root/test1.txt ]; then echo ok; fi

In shell scripts, there is a common way to use if to judge logic, which is case. The specific format is:

case  变量  invalue1)          command          ;;value2)          command          ;;value3)          command          ;;*)          command          ;;esac

The above structure, which does not limit the number of * values, represents a value other than value above. Write a script that determines whether the input value is odd or even:

[[email protected] sbin]# cat case.sh#! /bin/bashread -p "Input a number: " na=$[$n%2]case $a in    1)        echo "The number is odd."        ;;    0)        echo "The number is even."        ;;    *)        echo "It‘s not a number!"        ;;esac

The value of $a is either 1 or 0, and the result is:

[[email protected] sbin]# sh case.shInput a number: 100The number is even.[[email protected] sbin]# sh case.shInput a number: 101The number is odd.

Case scripts are often used to write startup scripts for system services, such as those used in/etc/init.d/iptables, so you might want to check them out.

Loops in a shell script

The shell script is also a simple programming language, of course, the loop is not missing. The commonly used loops have a for loop and a while loop. The structure of the two loops is described below.

    1. For loop
[[email protected] sbin]# cat for.sh#!  /bin/bashfor i in `seq 1 5`; do    echo $idone

A sequence in the script that seq 1 5 represents from 1 to 5. You can run this command directly and try it. The result of the script execution is:

[[email protected] sbin]# sh for.sh12345

With this script you can see the basic structure of the For loop:

The condition of the for variable name in the loop;
Command
Done

The "condition of the loop" here can be written as a set of strings or numbers (separated by 1 or more spaces), or it can be the result of a command's execution:

[[email protected] sbin]# for i in 1 2 3 a b; do echo $i; done123ab

You can also write the execution results of a reference system command, just like that seq 1 5 but need to be enclosed in anti-quotes:

[[email protected] sbin]# for file in `ls`; do echo $file; donecase.shfirst.shfor.shif1.shif2.shif3.shoption.shread.shsum.shvariable.sh
    1. While loop
[[email protected] sbin]# cat while.sh#! /bin/basha=5while [ $a -ge 1 ]; do    echo $a    a=$[$a-1]done

The while loop format is also simple:

While condition; Do

      command

Done

The above example script performs the following results:

[[email protected] sbin]# sh while.sh54321

Alternatively, you can replace the loop condition with a colon, so that you can do a dead loop and often write a monitoring script like this:

while :; do    command    sleep 3done
Functions in a shell script

If you have learned to develop, you must know the function. If you have just come into contact with this concept, there is no relationship, in fact, very well understood. The function is to organize a piece of code into a small unit, and give the small unit a name, when the code is used to call the name of the small unit directly. Sometimes a paragraph in the script is always reused, and if written as a function, use the function name instead of each time, saving time and space.

Here is a simple shell script with functions:

[[email protected] sbin]# cat func.sh#! /bin/bashfunction sum(){    sum=$[$1+$2]    echo $sum}sum $1 $2

The results of the implementation are as follows:

[[email protected] sbin]# sh func.sh 1 23

The sum () in func.sh is a custom function in which the shell script function is formatted as:

Function name () {

Command

}

One thing to remind you, in a shell script, the function must be written in the front, not in the middle or the last, because the function is to be called, if it has not yet been called, it will certainly be wrong.

Shll Script Exercises

Shell scripts generally introduce so much, and the examples are the most basic, so even if you take all the examples completely, it doesn't mean how good your shell scripting ability is. So for the rest of the day, try to practice more, write more scripts, write more scripts, and your shell scripts will be more powerful. I hope you can find a book that specializes in shell scripting in-depth study it. Then you'll leave a few shell script exercises, you'd better not be lazy.

    1. Write a shell script that calculates the 1-100 and;
    2. Write the shell script, ask to enter a number, and then calculate from 1 to the input number and, if the input number is less than 1, then re-enter until the correct number is entered;
    3. Write shell scripts to copy all directories under the/root/directory (only one level) to the/tmp/directory;
    4. Write shell scripts, batch build user user_00, user_01, ... user_100 and all users belong to the Users group;
    5. Write a shell script that intercepts the first column in the line containing the keyword ' abc ' in the file Test.log (assuming the delimiter is ":"), then sorts the intercepted numbers (assuming the first column is a number), and then prints out the columns with more than 10 repetitions;
    6. Write the shell script to determine if the IP input is correct (IP rules are, N1.N2.N3.N4, where 1<n1<255, 0<n2<255, 0<n3<255, 0<n4<255).

Exercise Answer:

1.

#! /bin/bashsum=0for i in `seq 1 100`; do        sum=$[$i+$sum]doneecho $sum

2.

#! /bin/bashn=0while [ $n -lt "1" ]; do        read -p "Please input a number, it must greater than "1":" ndonesum=0for i in `seq 1 $n`; do        sum=$[$i+$sum]doneecho $sum

3.

#! /bin/bashcd /rootfor f in `ls `; do        if [ -d $f ] ; then                cp -r $f /tmp/        fidone

4.

#! /bin/bashgroupadd usersfor i in `seq 0 9`; do        useradd -g users user_0$idonefor j in `seq 10 100`; do        useradd -g users user_$jdone

5.

#! /bin/bashawk -F‘:‘ ‘$0~/abc/ {print $1}‘ test.log >/tmp/n.txtsort -n n.txt |uniq -c |sort -n >/tmp/n2.txtawk ‘$1>10 {print $2}‘ /tmp/n2.txt

6.

#! /bin/bashcheckip() {        if echo $1 |egrep -q ‘^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$‘ ; then                a=`echo $1 | awk -F. ‘{print $1}‘`                b=`echo $1 | awk -F. ‘{print $2}‘`                c=`echo $1 | awk -F. ‘{print $3}‘`                d=`echo $1 | awk -F. ‘{print $4}‘`                for n in $a $b $c $d; do                        if [ $n -ge 255 ] || [ $n -le 0 ]; then                                echo "the number of the IP should less than 255 and greate than 0"                                return 2                        fi                done        else                echo "The IP you input is something wrong, the format is like 192.168.100.1"                return 1        fi}rs=1while [ $rs -gt 0 ]; do    read -p  "Please input the ip:" ip    checkip $ip    rs=`echo $?`doneecho "The IP is right!"

Review shell scripts

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.