Here we will first introduce the basic syntax of shell, including the beginning, comment, variables, and environment variables, however, laying a good foundation is a prerequisite for easy learning in the future.
1. Linux script compiling Basics
◆ 1.1 Basic syntax Introduction
Start with 1.1.1
The program must start with the following line (must begin with the first line of the file ):
#! /Bin/sh
Symbol #! The parameter used to tell the system that the program is used to execute the file. In this example, we use/bin/sh to execute the program.
When editing a script, you must make it executable if you want to execute it.
To make the script executable:
Compile chmod + x filename to run it with./filename.
1.1.2 notes
During shell programming, a sentence starting with # represents a comment until the end of this line. We sincerely recommend that you use annotations in your program.
If you have used annotations, you can understand the role and working principle of the script in a short time even if the script is not used for a long time.
1.1.3 Variables
You must use variables in other programming languages. In shell programming, all variables are composed of strings, and you do not need to declare variables. To assign a value to a variable, you can write as follows:
Copy codeThe Code is as follows :#! /Bin/sh
# Assign values to variables:
A = "hello world"
# Print the content of variable:
Echo "A is :"
Echo $
Sometimes the variable name is easily confused with other words, such:
Copy codeThe Code is as follows: num = 2
Echo "this is the $ numnd"
This does not print "this is the 2nd", but only prints "this is the", because shell will search for the value of the variable numnd, but there is no value for this variable. We can use curly braces to tell shell that we want to print the num variable:
Copy codeThe Code is as follows: num = 2
Echo "this is the $ {num} nd"
This will print: this is the 2nd
1.1.4 Environment Variables
Variables processed by the export keyword are called environment variables. We will not discuss environment variables, because generally, only environment variables are used in the login script.
This article introduces the actual Linux shell script.
Introduction to basic Linux shell script Learning (2)
This section introduces the basic course of Linux shell script. It introduces shell commands and process control in detail. This section introduces three types of commands, which should be compared during learning.
The basic course of Linux shell script describes the beginning, comments, variables, and environment variables of the basic syntax. Here we will introduce the first part of the shell command and control process, three types of commands can be used in shell scripts, but the control process should be put in the next lecture.
1.1.5 Shell command and Process Control
Three types of commands can be used in shell scripts:
1) Unix command:
Although any unix command can be used in shell scripts, some more common commands are used. These commands are usually used for file and text operations.
Common command syntax and functions
Echo "some text": print the text on the screen
Ls: file list
Wc-l filewc-w filewc-c file: calculate the number of file lines. Calculate the number of words in the file. Calculate the number of characters in the file.
Cp sourcefile destfile: file copy
Mv oldname newname: rename a file or move a file
Rm file: delete an object
Grep 'pattern' file: searches for strings in a file, for example, grep 'searchstring' file.txt.
Cut-B colnum file: specify the content range of the file to be displayed, and output them to the standard output device, for example: output 5th to 9th characters in each line cut-b5-9 file.txt do not confuse with cat command, this is two completely different commands
Cat file.txt: output file content to the standard output device (screen)
File somefile: get the file type
Read var: prompt the user to input and assign the input value to the variable.
Sort file.txt: sorts the rows in the file.txt file.
Uniq: Delete the columns in a text file, for example, sort file.txt | uniq
Expr: perform mathematical operations Example: add 2 and 3 expr 2 "+" 3
Find: search for a file. For example, search for find.-name filename-print based on the file name.
Tee: outputs data to the standard output device (screen) and files such as: somecommand | tee outfile
Basename file: returns a file name that does not contain a path, for example, basename/bin/tux.
Dirname file: the path of the returned file. For example, dirname/bin/tux will return/bin.
Head file: prints the first few lines of a text file.
Tail file: number of rows at the end of a text file
Sed: Sed is a basic search replacement program. You can read text from standard input (such as command pipeline) and
The result is output to the standard output (screen ). This command uses a regular expression (see references) for search. Do not confuse with wildcards in shell. For example, replace linuxfocus with LinuxFocus: cat text. file | sed's/linuxfocus/LinuxFocus/'> newtext. fileawk: awk to extract fields from text files. By default, the field delimiter is a space. You can use-F to specify other separators.
Cat file.txt | awk-F, '{print $1 "," $3}', which is used here as a field delimiter and prints both the First and Third fields. If the file contains the following content: Adam Bor, 34, IndiaKerry Miller, 22, and USA, the output result is Adam Bor, IndiaKerry Miller, USA.
2) concept: pipelines, redirection, and backtick
These are not system commands, but they are really important.
The pipeline (|) uses the output of a command as the input of another command.
Grep "hello" file.txt | wc-l
Search for a row containing "hello" in file.txt and calculate the number of rows.
Here, the grep command output serves as the wc command input. Of course, you can use multiple commands.
Redirection: output the command result to a file instead of a standard output (screen ).
> Write the file and overwrite the old file
> Add it to the end of the file to retain the content of the old file.
Backlash
You can use a backslash to output a command as a command line parameter of another command.
Command:
Find.-mtime-1-type f-print
Used to search for files modified in the past 24 hours (-mtime-2 indicates the past 48 hours. If you want to pack all the searched files, you can use the following script:
#! /Bin/sh
# The ticks are backticks (') not normal quotes ('):
Tar-zcvf lastmod.tar.gz 'Find.-mtime-1-type f-print'
Next, let's talk about the basic learning of Linux shell scripts. We will continue to talk about the control process.
Linux shell script basic learning (3)
The first two lectures on Linux shell script have been completed, but we haven't had time to talk about the control process. Here we will control the three parts of the process if, case, and select.
Linux shell script basic learning Lecture 3: When we introduced shell commands and Process Control in the previous section, we could not talk about process control due to space limitations, today, we will only introduce the first three parts of if case and select. The following three parts can only be introduced in the fourth lecture of Linux shell script basics.
1.1.5 Shell command and Process Control (2)
3) Process Control
1. if
If the expression "if" is true, the part after then is executed:
If...; then
....
Elif...; then
....
Else
....
Fi
In most cases, you can use test commands to test the conditions. For example, you can compare strings, determine whether a file exists, and whether the file is readable...
"[]" Is usually used to represent a conditional test. Note that spaces are important. Make sure that the square brackets have spaces.
[-F "somefile"]: determines whether it is a file.
[-X "/bin/ls"]: determines whether/bin/ls exists and has the executable permission.
[-N "$ var"]: determines whether the $ var variable has a value.
["$ A" = "$ B"]: determines whether $ a and $ B are equal.
Run man test to view all types of test expressions that can be compared and judged.
Directly execute the following script:
#! /Bin/sh
If ["$ SHELL" = "/bin/bash"]; then
Echo "your login shell is the bash (bourne again shell )"
Else
Echo "your login shell is not bash but $ SHELL"
Fi
The variable $ SHELL contains the name of the logon shell. We compared it with/bin/bash.
Shortcut Operators
If you are familiar with the C language, you may like the following expressions:
[-F "/etc/shadow"] & echo "This computer uses shadow passwors"
Here & is a shortcut operator. If the expression on the left is true, execute the Statement on the right.
You can also think of it as a logical operation. In the above example, if the/etc/shadow file exists, print "This computer uses shadow passwors ". Similarly, operations (|) are also available in shell programming. Here is an example:
#! /Bin/sh
Mailfolder =/var/spool/mail/james
[-R "$ mailfolder"] ''{echo" Can not read $ mailfolder "; exit 1 ;}
Echo "$ mailfolder has mail from :"
Grep "^ From" $ mailfolder
The script first checks whether mailfolder is readable. If it is readable, the "From" line in the file is printed. If it is not readable or the operation takes effect, print the error message and exit the script. There is a problem here, that is, we must have two commands:
-Print the error message.
-Exit the program.
We use curly braces to put the two commands together as one command in the form of an anonymous function. General functions will be mentioned below.
We can use the if expression to do anything without the sum or operator, but it is much more convenient to use the sum or operator.
2. case
Case: The expression can be used to match a given string, not a number.
Case... in
...) Do something here ;;
Esac
Let's look at an example. The file command can identify the file type of a given file, for example:
File lf.gz
This will return:
Lf.gz: gzip compressed data, deflated, original filename,
Last modified: Mon Aug 27 23:09:18 2001, OS: Unix
We use this to write a script named smartzip, which can automatically decompress bzip2, gzip, and zip compressed files:
#! /Bin/sh
Ftype = 'file "$1 "'
Case "$ ftype" in
"$1: Zip archive "*)
Unzip "$1 ";;
"$1: gzip compressed "*)
Gunzip "$1 ";;
"$1: bzip2 compressed "*)
Bunzip2 "$1 ";;
*) Echo "File $1 can not be uncompressed with smartzip ";;
Esac
You may notice that we use a special variable $1 here. The variable contains the first parameter value passed to the program.
That is, when we run:
Smartzip articles.zip
$1 is the string articles.zip
3. selsect
The select expression is a bash extension application, especially for interactive use. You can select from a group of different values.
Select var in...; do
Break
Done
... Now $ var can be used ....
The following is an example:
#! /Bin/sh
Echo "What is your favorite OS? "
Select var in "Linux" "Gnu Hurd" "Free BSD" "Other"; do
Break
Done
Echo "You have selected $ var"
The following is the result of running the script:
What is your favorite OS?
1) Linux
2) Gnu Hurd
3) Free BSD
4) Other
#? 1
You have selected Linux
The above is the content of this lecture. There are many control procedures. Here we will first introduce these three.
Detailed introduction to basic Linux shell script Learning (4)
Linux shell script Base 4: Next we will learn the control process content in the Linux shell script. Here we will mainly introduce the loop and quotation marks of the control process.
In the previous basic Linux shell script study, we talked about if, select, and case of the process in the Linux shell script. Here we will introduce the loop and quotation marks of the Linux shell script control process, the control process contains many contents, and some of the content is about the here document.
4. loop
Loop expression:
While...; do
....
Done
While-loop will run until the expression test is true. Will run while the expression that we test for is true.
The keyword "break" is used to jump out of the loop. The keyword "continue" is used to directly jump to the next loop without executing the remaining part.
The for-loop expression is used to view a string list (strings are separated by spaces) and then assigned to a variable:
For var in...; do
....
Done
In the following example, ABC is printed to the screen:
#! /Bin/sh
For var in a B C; do
Echo "var is $ var"
Done
The following is a more useful script showrpm. Its function is to print statistics of some RPM packages:
#! /Bin/sh
# List a content summary of a number of RPM packages
# USAGE: showrpm rpmfile1 rpmfile2...
# EXAMPLE: showrpm/cdrom/RedHat/RPMS/*. rpm
For rpmpackage in $ *; do
If [-r "$ rpmpackage"]; then
Echo "=====================$ rpmpackage ===================="
Rpm-qi-p $ rpmpackage
Else
Echo "ERROR: cannot read file $ rpmpackage"
Fi
Done
The second special variable $ * is displayed, which contains all input command line parameter values.
If you run showrpm openssh. rpm w3m. rpm webgrep. rpm
$ * Contains three strings: openssh. rpm, w3m. rpm, and webgrep. rpm.
5. quotation marks
Before passing any parameters to a program, the program extends the wildcards and variables. Here, the extension means that the program will replace the wildcard (for example, *) with the appropriate file name, and replace the variable with the variable value. To prevent this type of replacement, you can use quotation marks: Let's take a look at an example. Suppose there are some files in the current directory, two jpg files, mail.jpg and tux.jpg.
1.2 compile SHELL scripts
# Ch #! /Bin/sh mod + x filename
Cho *. jpg is slow. Why ?. /Filename to execute your script.
This will print the result of "mail.jpg tux.jpg.
Quotation marks (single quotation marks and double quotation marks) will prevent such wildcard extension:
#! /Bin/sh
Echo "*. jpg"
Echo '*. jpg'
This will print "*. jpg" twice.
Single quotes are stricter. It can prevent any variable extension. Double quotation marks can prevent wildcard extension but allow variable extension.
#! /Bin/sh
Echo $ SHELL
Echo "$ SHELL"
Echo '$ shell'
The running result is:
/Bin/bash
/Bin/bash
$ SHELL
Finally, there is also a method to prevent this extension, that is, to use the Escape Character -- reverse oblique ROD:
Echo *. jpg
Echo $ SHELL
This will output:
*. Jpg
$ SHELL
Here is the Linux shell script basics. the control process also includes the content of the here document for further analysis.