Linux (8) -- shell programming

Source: Internet
Author: User

 

 

A simple ShellProgram

Let's look at a shell program.

-----------------

 
#! /Bin/sh # this is to show what a example looks like. echo "our first example" Echo # This inserts an empty line in outputecho "we are currently in the following directory. "/bin/pwdechoecho" this directory contains the following files "/bin/ls 

Shell Structure:

#! /Bin/sh
The following script is interpreted and executed using the Bourne shell interpreter in the system. #! Is a special identifier, followed by the path of the shell that explains the script.

# Comment row
This line of content serves as a comment, and the content will not be executed

Echo output statement
Equivalent to print output in programming

/Bin/pwd display current path
PWD is commonly used. Add/bin/to the front to indicate the absolute path of this command.

/Bin/ls display the content in the current directory
This is not explained. It should be the first to know about Linux.

 

Run the following command:
[Root @ bogon bin] #Sh exple. Sh
Out first example --- print content

We are currently in the following directory. --- print the content
/Bin --- display the current path

This directory contains the following files ----- print content
Alsaunmute date gettext mail red touch --- display files in the current directory
Arch dd grep mailx RM tracepath
Ash DF gtar mkdir rmdir tracepath6
Ash. Static dmesg gunzip mknod RPM Traceroute
Aumix-Minimal dnsdomainname gzip mktemp RVI traceroute6
Awk doexec hostname more rview true
Basename domainname igawk Mount sed exple. Sh

 

It is very simple. This is the simplest shell programming, but it is just to integrate some of the commands I usually use together. I don't know if you are familiar with the batch processing in DOS. Similar to them, they all put a group of commands for our smooth operation together for execution. Shell is an explanatory language.
In fact, we will find that such programming is highly dependent on our system. For example, run the/bin/PWD command. If PWD is not stored in the bin/directory on your system, an error may occur when the program runs here.
A more formal explanation:
Shell is basically a command interpreter, similar to command.com in DOS. It receives user commands (such as LS) and then calls the corresponding application. The common shells include standard Bourne shell (SH) and c shell (CSH ).

Interactive Shell and non-interactive shell

In interactive mode, shell waits for your input and runs the command you submit. This mode is called interactive because shell interacts with users. This mode is also very familiar to most users: logon, command execution, and logout. When you sign back, shell is terminated.
Shell can also run in another mode: non-interactive mode. In this mode, shell does not interact with you, But reads commands stored in files and runs them. When it reads the end of the file, shell is terminated.

To create a shell program:

Step 1: create a file that contains commands and control structures.
Step 2: Modify the permission of the file so that it can be executed.
Of course, if a user wants to execute a file, the user must have the permission to execute the file.
Run the "chmod U + X" command to grant the execution permission to the user.
Step 3: Execute./example to directly execute the file in the current directory
You can also run the "Sh example" command.

Shell variable

Do we have a preliminary understanding of shell? Is it just a simple command set? No! As a language, he also has his own syntax. If you know any language as follows, let's look at the differences between shell and the language you know.

 

Variable: A method used by Shell to transmit data. It represents the symbolic name of each value.

Shell has two types of variables:Temporary and Permanent Variables

Temporary VariableIt is defined inside the shell program. Its scope of use is limited to the program that defines it and is invisible to other programs.
Including User-Defined variables and location variables.
Format requirements for custom variables:
It is a string of letters, numbers, or underscores that start with a letter or underscore and have different meanings. Variable name length is not limited.
When using a variable, you must add the prefix "$" before the variable name (I remember PHP loves this symbol ^_^)
Generally, variable names are capitalized.
For example:
Mum = 100 value assignment
Time = $ (date) Assign the execution result of a command to the variable,
A = $ B copy a variable to another variable

Define and view a variable:
[Root @ bogon ~] #Num = 100
[Root @ bogon ~] #Echo $ num
100
[Root @ bogon ~] #Time = $ (date)
[Root @ bogon ~] #Echo $ time
March 13, June 1 22:57:28 CST 2012
[Root @ bogon ~] #B = fnngj
[Root @ bogon ~] #Echo $ B
Fnngj
[Root @ bogon ~] #A = $ B
[Root @ bogon ~] #Echo $
Fnngj

Permanent variableIs an environment variable, and its value does not disappear with the execution of shell scripts.
[Root @ bogon ~] # Echo $ Lang
Zh_CN.UTF-8
[Root @ bogon ~] # Echo $ path
/Usr/Kerberos/sbin:/usr/Kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin: /usr/bin:/usr/x11r6/bin:/root/bin
These System configurations will certainly not disappear as my shell program ends.

Let's take a look at the variables defined in our system:
[Root @ bogon ~] #Set | more
A = fnngj
B = fnngj
Bash =/bin/bash
Bash_argc = ()
Bash_argv = ()
Bash_lineno = ()
Bash_source = ()
Bash_versinfo = ([0] = "3" [1] = "00" [2] = "15" [3] = "1" [4] = "release" [5] = "i686-redhat-
Linux-GNU ")
Bash_version = '3. 00.15 (1)-release'
Colors =/etc/dir_colors.xterm
Columns = 80
.............

Delete variable:
[Root @ bogon ~] # Unset
Run the unset command to delete a variable.

 

READ command

This command is interesting, but it is also very common. For example, when a program runs on a sentence, it stops and requires the user to enter the content, and then continues to execute the Command Based on the content entered by the user.

READ command: reads data from the keyboard and assigns values to variables.
For example, read usernsme

[Root @ bogon shell] #Touch read. Sh
[Root @ bogon shell] #VI read. Sh

 
#! /Bin/shread first second thirdecho "the first parameter is $ first" Echo "the second parameter is $ second" Echo "The third parameter is $ third"

 

 

[Root @ bogon shell] #Sh read. Sh
100 200 300 ---------------You must enter parameters here.
The first parameter is 100
The second parameter is 200
The third parameter is 300

Shell variable arithmetic operations

 

Arithmetic Operations are also frequently used. Let's look at Shell simple addition, subtraction, multiplication, division.

Expr command: arithmetic operation on Integer Variables
For example:
[Root @ localhost ~] # Expr 3 + 5
3 + 5
[Root @ localhost ~] # Expr 3 + 5
8
[Root @ localhost ~] # Expr 9-5
4
[Root @ localhost ~] * Expr 9/5
1
[Root @ localhost ~] # Expr 9 \ * 5
45
This division is division, so 9 Division 5 equals 1, directly ignoring the remaining 4.
This multiplication is because the asterisk (*) has other meanings. For example, when you search for an asterisk (*), * represents an unknown character. Therefore, if you want to use it as a multiplication character, here we need to add the escape symbol (\)

 

A shell instance 

 

We have talked about the task plan. Now we can write a meaningful shell program based on the task plan.
There is a very junk Apache server in a school. There are a lot of students accessing this server from to. Then, this server Often crashes, and the school has no money to add equipment. Now, let's write a shell program to check Apache every two minutes. If the server crashes. Restart the instance. (Of course, this cannot solve this problem from the perspective of the subject)

How can I determine whether an Apache server is started?
[Root @ bogon bin] #Pgrep httpd
7942 7944 7946 7947 7948 7950
If the server has crashed, the input pgrep httpd will have no input.

Now that we know the judgment method, we can start to write the program test. Apache.
-------------------------------

 
#! /Bin/sh # "if .... else "usage # using this program to show your system's service. echo "now, the web services of this Linux system will be detect... "Echo # detesct WWW serviceweb = '/usr/bin/pgrep httpd' If [" $ web "! = ""] Thenecho "the Web sercice is running." elseecho "the Web sercice is running."/etc/rc. d/init. d/httpd startfi

 

-----------------------------------
In fact, the core content is to execute the restart command to determine whether pgrep httpd is empty. ^_^!

For task plans, see Chapter 6 process management in Linux.
The meaning of the above parameters: http://www.cnblogs.com/fnng/archive/2012/05/20/2510641.html

[Root @ bogon test] # crontab-e
*/2 20-22 ** 1-7 test. Apache

: WQ!
Save and exit.
Then there is nothing to do with us. Execute the script as planned. Haha!

Bytes --------------------------------------------------------------------------------------------------------

Postscript:

Shell programming is rarely introduced here, and even loop statements (if... else) are not introduced. The last example is used. Shell programming can be a thick and thick book. However, it is not my current learning focus. If you have time, I will add another shell.

Since the beginning of this year, learning Linux has come to an end. In fact, many problems have been encountered during the learning process. This "Linux thing" only sorts out the main content I learned. I'm glad that I have learned a little about Linux. However, I think it takes too long to learn about it. Maybe I can write it in a month or two. This year, I had a job change from the North to the South. Now, my work is very busy and there are too many things in my life. Therefore, the learning time is low. However, I will continue to write my work and study here.

The following learning will be done in two aspects: Oracle and performance testing.

I have always been a database idiot and have little interest in databases. However, it is a shortcoming of my technological development. Therefore, I want to spend some time learning this knowledge.

Performance testing has always been my favorite aspect. Currently, no performance tests are available. However, I have performed performance in the previous job. The next goal is to perform professional performance tests. Both LoadRunner and jmeter have been used. However, I will focus on the theoretical basis. The focus of performance testing is not on tools, but on a wide range of knowledge. Some things are recorded here. Haha!

 

 

 

 

 

 

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.