From a programmer's point of view , Shell Itself is a kind of use C A program written in a language , From the user's point of view ,Shell It's users and Linux Operating system communication bridge . Users can either enter commands to execute , It can be used again Shell scripting , To perform more complex operations . stay Linux GUI Today's increasingly perfect , In the field of system management ,Shell Programming still plays an important role . Deeply understand and skillfully grasp Shell Programming , Is each Linux Users are required to Lesson one .

Linux Of Shell There are many kinds , Common are :Bourne Shell(/usr/bin/sh or /bin/sh)、Bourne Again Shell(/bin/bash)、C Shell(/usr/bin/csh)、K Shell(/usr/bin/ksh)、Shell for Root(/sbin/sh), wait . Different Shell The grammar of a language is different , So you can't swap . Each of these Shell They all have their own characteristics , Basically , Master any of them That's enough . In this paper , Our focus is on Bash, That is to say Bourne Again Shell, Because it's easy to use and free ,Bash It is widely used in daily work ; meanwhile ,Bash And most of them Linux By default Shell. In general , People don't differentiate Bourne Shell and Bourne Again Shell, therefore , In the text below , We can see #!/bin/sh, It can also be changed to #!/bin/bash.

utilize vi Wait for the text editor to write Shell The format of the script is fixed , as follows :



Your commands go here

The symbol in the first line #! Tell the system that the program specified by the path is to interpret the script file Shell cheng order . If it's not in the first line , When executing script files , There will be mistakes . The next part is the main program ,Shell Scripts are like high-level languages , There are also variable assignments , There are also control statements . In addition to Out of line , With # The first line is the comment line , Until the end of the trip . If a line is incomplete , You can add... At the end of the line ", This symbol indicates that the next line and this line will merge into the same line .

Finished editing , Save the script as, File name suffix sh That means this is one Bash Script files . When executing a script , First, change the properties of the script file to executable :

chmod +x

The way to execute a script is :


Let's start with the classic “hello world” Starting with , Take a look at the simplest Shell What the script looks like .


#print hello world in the console window

a = "hello world"

echo $a

Shell Script Is a weakly typed language , When you use a variable, you don't need to declare its type first . The new variable will be stored in memory allocated in the local data area , This variable returns to the current Shell all , Any child into Programs cannot access local variables . These variables are different from environment variables , Environment variables are stored in another memory area , It's called the user environment zone , This variable in memory can be accessed by the child process . The way variables are assigned is :

variable_name = variable_value

If you assign a value to a variable that already has a value , The new value will replace the old value . When you take a value, you should add... Before the variable name $,$variable_name You can use... In quotation marks , This is obviously different from other high-level languages . If there is confusion , You can use curly braces to distinguish , for example :

echo "Hi, $as"

It won't output “Hi, hello worlds”, It's the output “Hi,”. This is because Shell hold $as As a variable , and $as Not assigned , Its value is empty. . The right way is :

echo "Hi, ${a}s"

Variables in single quotation marks do not perform variable substitution operations .

About variables , We need to know a few more about it Linux command .

env Used to display variables and their values in the user environment area ;set Used to display variables and their values in local data area and user environment area ;unset Used to delete the current value of the specified variable , The value will be specified as NULL;export The command is used to transfer variables from the local data area to the user environment area .

Let's take a more complex example , With this example , Let's talk about Shell Script The grammar of .

 1 #!/bin/bash
 2 # we have less than 3 arguments. Print the help text:
 3 if [ $# -lt 3 ]; then
 4 cat<<HELP
 5      ren -- renames a number of files using sed regular expressions
 7      USAGE: ren 'regexp' 'replacement' files
 8      EXAMPLE: rename all *.HTM files in *.html:
 9      ren 'HTM$' 'html' *.HTM
12      exit 0
13 fi
14 OLD="$1"
15 NEW="$2"
16 # The shift command removes one argument from the list of
17 # command line arguments.
18 shift
19 shift
20 # $* contains now all the files:
21 for file in $*; do
22 if [ -f "$file" ]; then
23     newfile=`echo "$file" | sed  "s/${OLD}/${NEW}/g"`
24         if [ -f "$newfile" ]; then
25             echo "ERROR: $newfile exists already"
26         else
27             echo "renaming $file to $newfile "
28             mv "$file" "$newfile"
29         fi
30 fi
31 done


Let's look at it from the beginning , As explained in the previous example on the first two lines , Start with the third line , There's something new .if Statements are similar to other programming languages , It's all process control statements . The syntax is :

if …; then

elif …; then



Different from other languages ,Shell Script in if The conditional part of the statement is separated by a semicolon . In the third line [] A conditional test , There are several common conditional tests :

[ -f "$file" ] Judge $file Is it a file

[ $a -lt 3 ] Judge $a Is the value of less than 3, Again -gt and -le Greater than or less than or equal to

[ -x "$file" ] Judge $file Whether it exists and has executable permissions , Again -r Test file readability

[ -n "$a" ] Judgment variable $a If there is a value , Test empty string with -z

[ "$a" = "$b" ] Judge $a and $b Whether the values of are equal

[ cond1 -a cond2 ] Judge cond1 and cond2 Is it true at the same time ,-o Express cond1 and cond2 There was a time when

Pay attention to the spaces in the conditional test section . There are spaces on both sides of the square brackets , stay -f、-lt、= There are also spaces on both sides of the symbol . Without these spaces ,Shell There are errors when interpreting scripts .

$# Means to include $0 The number of command line arguments inside . stay Shell in , The script name itself is $0, The rest, in turn, are $0、$1、$2…、${10}、${11}, wait .$* Represents the entire parameter list , barring $0, That is to say, the parameter list does not include the file name .

Now we understand that the third line means that if the script file has fewer than three parameters , execute if and fi Between sentences The content of . then , The content between lines four and eleven is Shell Script Programming is called Here file ,Here Documents are used to pass multiple lines of text to a command .Here The format of the document is << Start , Followed by a string , stay Here At the end of the document , This string will also appear , Indicates the end of the document . In this case ,Here The document is output to cat command , Also print the document content on the screen , Display help The role of information .

On line 12 exit yes Linux The order of , Exit the current process . stay Shell All of them can be used in scripts Linux command , Use the above cat and exit, On the one hand , Skillfully use Linux Orders can also be greatly reduced Shell The length of the script .

fourteen 、 Fifteen two sentences are assignment sentences , Assign the first and second parameters to the variable respectively OLD and NEW. The next two sentences are notes , Note the following two shift The function of is to delete the first and second parameter in the parameter list , The later parameters become the new first and second parameters in turn , Note that the parameter list does not include $0.

then , From line 21 to line 31 is a circular statement .Shell Script There are several formats for loops in :

while [ cond1 ] && { || } [ cond2 ] …; do


for var in …; do


for (( cond1; cond2; cond3 )) do


until [ cond1 ] && { || } [ cond2 ] …; do


In the above cycles , You can also use something like C In language break and continue Statement break The current loop operation . The loop in line 21 is to put the parameters in the parameter list one by one into the variable file in . Then enter the cycle , Judge file Is it a file , If it's a file , Then use sed Command to search and generate new file names .sed It's basically a search and replace program , From standard input , For example, pipes read in text , And output the result to the standard output ,sed Using regular expressions To search . In line 23 ,backtick(`) The purpose of this is to take out two backtick The command output between , ad locum , That is to say, take out the result and assign it to the variable newfile. thereafter , Judge newfile Does it already exist , Otherwise, I will file Change to newfile. So we can understand the role of this script ,Shell Script Other scripts written are similar to this , It's just that grammar and usage are slightly different .

Through this example, we can see that Shell Script Rules for writing , But there are a few things to tell .

first , except if Statements in ,Shell Script It's similar in C Multi branch structure in language case sentence , The syntax is :

case var in

pattern 1 )

… ;;

pattern 2 )

… ;;


… ;;



Let's take another example , have a look case Usage of sentences .

while getopts vc: OPTION


case $OPTION in


     ehco "$COPIES";;

v) echo "suyang";;

\?) exit 1;;



above getopts Be similar to C Functions provided by language getopts, stay Shell Script in ,getopts Often with while Statements are used together .getopts The grammar is as follows :

getopts option_string variable

option_string Contains a list of single character options , if getopts In the command line arguments Found hyphens , Then it will combine the character after the hyphen with option_string Compare , If the match is successful , Then we put the variable variable Set the value of to this option , If there is no match , Then put The value of the variable is set to ?. occasionally , Option also has a value , for example -c5 etc. , It's time to option_string Add a colon after the letter in ,getopts Found colon after , The value is read , Then put that value in a special variable OPTARG in . This command is more complicated , If necessary , Readers can refer to Shell Compilation of relevant materials .

The function of the above loop is to take out the options after the script name in turn , To deal with , If you enter an illegal option , entering "? The designated part , Exit the script program .

the second ,Bash Provides an extension for interactive applications select, Users can choose from a different set of values . The syntax is as follows :

select var in …; do



for example , The output of the following program is :


echo "Your choice?"

select var in "a" "b" "c"; do



echo $var


Your choice?

1) a

2) b

3) c

Third ,Shell Script You can also use custom functions in , Its grammatical form is as follows :




For example, we can put lines 4 to 12 in the second example above into a file named help Function body , After each call directly write help that will do . The way to handle function call parameters in a function is , Just use the above $1、$2 To represent the first respectively 、 The second parameter , use $* Represents a list of parameters .

Fourth , We can also do that Shell The debug Shell Script Script , Of course, the easiest way is to use echo Output to see the value of the variable .Bash It also provides real debugging methods , It's used when executing scripts -x Parameters .

sh ?x

This executes the script and displays the values of all variables in the script , You can also use parameters -n, It doesn't execute scripts , Just return all syntax errors .