An introductory tutorial on Linux shell scripting _linux Shell

Source: Internet
Author: User
Tags case statement first row

From a programmer's point of view, the shell itself is a program written in C language, from the user's point of view, the shell is the user and the Linux operating system communication Bridge. Users can either enter command execution and use shell scripting to accomplish more complex operations. In the Linux GUI increasingly perfect today, in the system management and other fields, shell programming still plays a role that can not be ignored. Deep understanding and mastery of shell programming is one of the required lessons for every Linux user.

Linux has a wide variety of shell types, common: 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), and so on. The syntax for different shell languages differs, so it is not interchangeable. Each shell has its own characteristics, and basically, mastering any of them is enough. In this article, our focus is on bash, the Bourne Again Shell, which is widely used in everyday work because of ease of use and free, and bash is also the default Shell for most Linux systems. Under normal circumstances, people do not distinguish between the Bourne shell and the Bourne Again shell, so in the following text, we can see #!/bin/sh, it can also be changed to #!/bin/bash.

The format for writing shell scripts using the vi text Editor is fixed, as follows:

Your commands Go

The symbol in the first line #! tells the system that the program that is specified by the following path is the shell program that interprets the script file. If the first row does not have this sentence, an error occurs when the script file is executed. The next part is the main program, and the shell script, like the high-level language, has variable assignments and control statements. Except for the first line, the line that begins with # is the comment line until the end of this row. If a row is not completed, you can add "at the end of the line", which indicates that the next row and this row will be merged into the same row.

After editing, save the script as, filename suffix sh indicates that this is a bash script file. To execute a script, you 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" and look at the simplest shell script.

#print Hello World in the console windows
a = "Hello World"
echo $a

Shell script is a weakly typed language that does not need to declare its type first when using variables. The new variable is allocated memory for storage in the local data area, which is owned by the current shell, and no child processes can access the local variables. These variables, unlike environment variables, are stored in another memory area, called the user environment, in which variables can be accessed by the quilt process. Variables are assigned in the following ways:

Variable_name = Variable_value

If you assign a value to a variable that already has a value, the new value replaces the old value. When you take a value, you add $ to the variable name, $variable _name can be used in quotes, which is significantly different from other high-level languages. If there is a confusion, you can use curly braces to differentiate, for example:

echo "Hi, $as"

Will not output "Hi, Hello Worlds", but output "Hi,". This is because the shell treats $as as a variable, and the $as is not assigned, and its value is empty. The correct approach is to:

echo "Hi, ${a}s"

Variables in single quotes do not have variable substitution operations.
For variables, you also need to know a few Linux commands associated with them.

Env is used to display the variables in the user's environment area and their values; set is used to display variables and their values in the local data area and user environment area; unset is used to delete the current value of the specified variable, which is specified as the Null;export command to transfer variables from the local data area to the user environment area.

Let's look at a more complex example, combined with this example, to describe the syntax of the shell script.

 # We have less than arguments. Print the Help text:
 if [$#-lt]; then

Let's look at it from the beginning, as explained in an example in the previous two lines, starting with the third line, with new content. If statements are similar to other programming languages, they are process control statements. Its syntax is:

If ...; Then ...
Elif ...; Then ...

Unlike other languages, the conditional portion of the IF statement in the Shell script is delimited by semicolons. The [] in the third row represents the conditional test, and the following are the common conditional tests:

[-F "$file"] to determine whether $file is a file

[$a-LT 3] to determine whether the value of $a is less than 3,-GT and-le, respectively, are greater than or less than equal

[-X ' $file] to determine whether $file exists and has executable permissions, as well--R test file readability

[-n ' $a] to determine whether the variable $a has a value, test the null string with the-Z

["$a" = "$b"] to determine whether the values of $a and $b are equal

[Cond1-a Cond2] Determines whether Cond1 and Cond2 are both established, and-o indicates that Cond1 and Cond2 have an established

Pay attention to the spaces in the conditional test section. There are spaces on both sides of the square brackets, as well as spaces on both sides of the symbol-F,-lt, =, and so on. Without these spaces, the shell would have an error interpreting the script.

The number of command line arguments #表示包括 $ $. In the shell, the script name itself is $ $, and the remainder is $, $, $ ..., ${10}, ${11}, and so on. $* represents the entire argument list, excluding $ $, which means that the argument list does not include the filename.

Now we understand that the third line means that if the script file has fewer than three parameters, the content between the IF and the FI statements is executed. Then, the content from lines fourth through 11th is called the here document in Shell script programming, where the document is used to pass multi-line text to a command. The format for here documents begins with <<, followed by a string, which also appears at the end of this document, indicating the end of the document. In this case, the here document is exported to the Cat command, and the contents of the document are printed on the screen to display help information.

Exit 12th is the Linux command, which means exiting the current process. You can use all of the Linux commands in your shell script, using cat and exit above, and on the one hand, being proficient with Linux commands can greatly reduce the length of your shell script.

14, 62 Sentences are assignment statements, respectively, the first and second parameters assigned to the variable old and new. The next two sentences are notes, note that the following two shift is to remove the first and second arguments in the list of arguments, and then to the new first and second parameters in turn, noting that the argument list does not include $ $.

Then, lines from 21 to 31 are a circular statement. The loops in the Shell script have the following formats:

While [Cond1] && {| |} [Cond2] ...; Do
Done with
var in ...;
Done for
((cond1; cond2 cond3))
do ... Done
until [Cond1] && {| |} [Cond2] ...; Do

In these loops, you can also interrupt the current loop operation using a break and continue statement similar to the C language. The loop in line 21st is to place the arguments in the argument list one by one into the variable file. Then enter the loop to determine if file is a file, and if so, search for and generate a new file name with the SED command. Sed can basically be viewed as a lookup replacement program that reads text from standard inputs, such as pipes, and outputs the results to standard output, and SED uses regular expressions to search. In line 23rd, the function of Backtick (') is to take out the output of the command between two Backtick, where the result is taken out and assigned to the variable newfile. Thereafter, judge whether NewFile already exists, or change file to NewFile. So we understand how this script works, and other scripts written by Shell script are similar to this, except that the syntax and usage are slightly different.

With this example we understand the rules of shell script writing, but there are a few things to tell.

First, in addition to the IF statement, the Shell script also has a case statement that resembles a multiple branching structure in C, and its syntax is:

Case Var in pattern
Pattern 2)
; Esac

Let's take a look at the use of case statements in the following example.

While getopts vc:option
c) copies= $OPTARG
   Ehco "$COPIES";;
V) echo "Suyang";;
\?) Exit 1;;
Esac done

The above getopts is similar to the function getopts provided by C language, in shell script, getopts is often combined with the while statement. The syntax for getopts is as follows:

Getopts option_string Variable

Option_string contains a string of single character options, if getopts found a hyphen in the command-line arguments, it compares the character after the hyphen to the option_string, and if the match succeeds, sets the value of the variable variable to that option, and if no match, The value of the variable is set to?. Sometimes, an option also takes a value, such as-C5, to be followed by a colon in the option_string, and getopts after the colon is found, the value is read and placed in a special variable optarg. This command is more complex and, if necessary, the reader can refer to the shell's written information in detail.

The function of the above loop is to sequentially remove the option after the script name, to process it, and if you enter an illegal option, enter the "? specified section to exit the script.

Second, Bash provides an extended select for interactive applications that users can choose from a different set of values. The syntax is as follows:

Select Var in ...; Do break

For example, the output of the following program is:

echo "Your choice?"
Select Var in "a" "B" "C"; Do-break-done
echo $var
Your choice?
1) a
2) b
3) C

Third, a custom function can also be used in Shell script in the form of the following syntax:

functionname ()

For example, we could put the fourth to 12th line in the second example above into a body called help function, and then write it directly at each call. The method used to handle function invocation parameters in a function is to represent the first and second arguments directly with the $ $ $ above, and the argument list with $*.

Four, we can also debug shell script scripts under the shell, of course, the simplest way is to use the Echo output view variable values. Bash also provides a true debugging method, which is to use the-x parameter when executing a script.

Sh. x

This executes the script and displays the values of all variables in the script, as well as parameter-N, which does not execute the script, but returns all the syntax errors.

The above is a small set to introduce the Linux Shell Script programming introductory tutorials all the content, I hope you like.

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: 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.