Linux Shell Script Programming Tutorial

Source: Internet
Author: User
Keywords shell script programming tutorial linux shell script programming tutorial programming shell script tutorial

So far, do you understand what a linux shell script is? If you understand it best, it doesn't matter if you don't understand. I believe that as you deepen your study, you will understand more and more about what a shell script is. First of all, it is a script and cannot be used as a formal programming language. Because it runs in the Linux shell, it is called a shell script. To put it bluntly, a shell script is a collection of commands. For example, I want to achieve this operation: 

1) enter the /tmp/ directory; 

2) list all file names in the current directory; 

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

4) delete All files in the current directory. 

The simple 4 steps requires you to type the command 4 times in the shell window and press Enter 4 times. Is this troublesome? Of course, these 4 steps are very simple. What if it is a more complex command setting that requires dozens of operations? It would be troublesome to type the keyboard one at a time. So you might as well record all operations in a document, and then call the commands in the document, so that one step can be completed. In fact, this document is a shell script, but this shell script has its special format.

Alibaba Cloud Simple Application Server:  Anti COVID-19 SME Enablement Program
$300 coupon package for all new SMEs and a $500 coupon for paying customers.

Shell scripts can help us to manage the server very conveniently, because we can specify a task plan to execute a certain shell script to meet our needs. This is a very proud thing for Linux system administrators. The current 139 mailbox is very easy to use. When sending an email, you can also send an email notification SMS to the user. Using this, we can deploy a monitoring shell script on our Linux server, such as the network card traffic is abnormal or the server When the web server is stopped, you can send an email to the administrator, and at the same time send an alarm message to the administrator so that we can know that the server has a problem in time.

There is a question that needs to be agreed. All custom scripts are recommended to be placed in the /usr/local/sbin/ directory. The purpose of this is to better manage documents; secondly, the administrator who takes over you will know Where to put custom scripts for easy maintenance.

[Basic structure of shell script and how to execute]
14_1.png.jpg
Shell scripts usually have a suffix of .sh. This does not mean that the script cannot be executed without .sh, but it is just a habit of everyone. So, if you find a file with a suffix of .sh in the future, it must be a shell script. The first line in test.sh must be "#! /bin/bash", which means that the file uses bash syntax. If this line is not set, your shell script cannot be executed. ’#’ means a comment, as mentioned earlier. Followed by some relevant comments of the script, as well as the author and creation date or version, etc. Of course, these comments are not necessary. If you are lazy, you can omit them, but the author does not recommend omitting them. Because as your working hours increase, you will write more and more shell scripts. If one day you look back at a script you wrote, you may forget what the script is for and when you wrote it. of. So it is necessary to write a comment. In addition, you are not the system administrator. If another administrator views your script, wouldn’t it be very depressing if he doesn’t understand it. Below the script is the command to be run.
14_7.png.jpg
Shell script execution is very simple, just "sh filename" directly, in addition, you can also execute it like this
14_8.png.jpg
By default, the document we edit with vim does not have execution permission, so you need to add an execution permission so that you can directly use ‘./filename’ to execute this script. In addition, when using the sh command to execute a shell script, you can add the -x option to view the execution process of the script, which will help us debug where the script is wrong.
14_9.png.jpg
The ‘date’ command is used in this shell script, and its function is to print the current system time. In fact, the date usage rate in shell scripts is very high. There are several options that I often use in shell scripts:
14_10.png.jpg
%Y means year, %m means month, %d means date, %H means hour, %M means minute, %S means second
14_11.png.jpg
Note the difference between %y and %Y.
14_21.png.jpgg

The -d option is also frequently used, it can print the date n days ago or n days later, of course, it can also print the date n months/years ago or later.

14_22.png.jpg

In addition, the day of the week is also commonly used

14_23.png.jpg

[Variables in shell scripts]

Using variables in shell scripts makes our scripts more professional and more like a language. Just kidding, variables are of course not for professionalism. If you write a 1000-line shell script, and a certain command or path appears hundreds of times in the script. Suddenly you feel that the path is wrong and want to change it. Wouldn't it be necessary to change it hundreds of times? Although you can use the batch replacement command, it is also very troublesome, and the script seems a lot bloated. The role of variables is used to solve this problem.

14_24.png.jpg

Backticks are used in test2.sh. Do you remember its function? 'D' and'd1' appear as variables in the script, and the format of defining the variable is "variable name=variable value". When referencing variables in scripts, you need to add the ‘$’ symbol, which is consistent with the custom variables in the shell mentioned earlier. Let's take a look at the results of the script execution.

14_25.png.jpg

Below we use the shell to calculate the sum of two numbers.

14_25.png.jpg

Mathematical calculations should be enclosed in ‘[ ]’ and a ‘$’ should be attached to the outside. The script result is:

14_26.png.jpg

Shell scripts can also interact with users.

14_27.png.jpg

This uses the read command, which can get the value of the variable from standard input, followed by the variable name. "Read x" means that the value of the x variable needs to be entered by the user through the keyboard. The script execution process is as follows:

14_28.png.jpg

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

14_29.png.jpg

There is a more concise way in test4.sh.
14_44.png.jpg

The read -p option is similar to echo. The execution is as follows:

14_45.png.jpg

Have you ever used such a command "/etc/init.d/iptables restart" The /etc/init.d/iptables file in front is actually a shell script, why can it be followed by a "restart"? This involves the shell The preset variables of the script. In fact, the shell script can be followed by variables during execution, and it can also be followed by multiple variables. I might as well write a script, and you will understand.

14_46.png.jpg

The execution process is as follows:

14_47.png.jpg

In the script, would you be wondering where the $1 and $2 come from, which are actually the default variables of the shell script, where the value of $1 is the 1 entered during execution, and the value of $2 is entered during execution $2, of course, there is no limit to the default variables of a shell script, this time you understand. There is also a $0, but it represents the name of the script itself. May wish to modify the script.

You must have guessed the execution result.

[Logical judgment in shell script]

If you have learned C or other languages, I believe you will not be unfamiliar with if. We can also use if logic to judge in shell scripts. The basic syntax of if judgment in the shell is:

1) Without else

if judgment statement; then

command

fi

The form ((a<60)) appears in if1.sh, which is a unique format in shell scripts. If you use a parenthesis or don't use it, you will get an error. Please remember this format. The execution result is:

2) With else

if judgment statement; then

command

else

command

fi

The execution result is:

14_54.png.jpg

[Functions in shell scripts]


If you have studied development, you must know what functions do. If you are new to this concept, it doesn't matter, it's actually easy to understand. The function is to organize a piece of code into a small unit, and give this small unit a name, when this code is used, it can directly call the name of the small unit. Sometimes a certain section of the script is always used repeatedly. If it is written as a function, it can be replaced by the function name every time it is used, which saves time and space.

The sum() in fun.sh is a custom function, which should be used in the shell script

function function name () {

command

}

Shell scripts are generally introduced so much. The examples given by the author are the most basic, so even if you have a complete grasp of all the examples, it does not mean how good your shell scripting ability is. So in the remaining days you should practice as much as possible and write more scripts. The more scripts you write, the stronger your ability will be. I hope you can find a book dedicated to shell scripting to study it in depth.
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.