Getting Started with Linux shell programming

Source: Internet
Author: User
Tags case statement

From the 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. The user can either enter command execution or use shell scripting to do more complicated operations. In the increasingly perfect Linux GUI today, in the field of system management, shell programming still plays a role that can not be ignored. An in-depth understanding and proficiency in shell programming is one of the required lessons for every Linux user.

There are many types of shell in Linux, 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. Different shell language syntax differs, so it cannot be exchanged for use. Each shell has its own characteristics, and basically, mastering either of these is enough. In this article, we focus on bash, the Bourne Again Shell, which is widely used in daily work due to ease of use and free, and bash is the default shell for most Linux systems. In general, people do not differentiate between the Bourne shell and the Bourne Again shell, so in the following text we can see #!/bin/sh, which can also be changed to #!/bin/bash.

The format for writing shell scripts using a text editor such as VI is fixed, as follows:

#!/bin/sh

#comments

Your commands go here

The symbol #! in the first line tells the system that the program specified by the subsequent path is the shell program that interprets the script file. If there is no such sentence in the first line, an error will occur when executing the script file. The next part is the main program, shell scripts like high-level languages, there are variable assignments, there are control statements. In addition to the first line, the line that begins with # is the comment line until the end of the line. If a row is not complete, you can add "at the end of the line, which indicates that the next line and row are merged into the same row .

After editing, save the script as filename. sh, file name suffix sh indicates that this is a bash script file. To execute the script, you first change the properties of the script file to executable:

chmod +x filename.sh

The way to execute the script is:

./filename.sh

Let's start with the classic "Hello World" and look at the simplest shell scripts.

#!/bin/sh

#print Hello World in the console window

A = "Hello World"

Echo $a

Shell script is a weakly typed language that uses variables without first declaring their type. The new variable is allocated memory in the local data area , which is owned by the current shell, and no child processes can access the local variable. These variables are different from environment variables, and environment variables are stored in another memory area called the User Environment area , and this memory variable can be accessed by the quilt process. variables are assigned in the following way:

Variable_name = Variable_value

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

echo "Hi, $as"

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

echo "Hi, ${a}S"

variables in single quotes do not perform variable substitution operations .

About variables, you also need to know several Linux commands associated with them.

env is used to display 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 will be specified as null The Export command is used to transfer variables in the local data area to the user environment area .

Let's look at a more complex example, and with this example, we'll tell the syntax of the shell script.

1 #!/bin/bash
2 # We have less than 3 arguments. Print the Help text:
3 If [$#-lt 3]; Then
4 Cat<5 Ren--renames a number of files using SED regular expressions
6
7 Usage:ren ' regexp ' replacement ' files
8 Example:rename all *. HTM files in *.html:
9 ren ' htm$ ' html ' *. Htm
10
Help
Exit 0
Fi
Old= "$"
New= "$"
# The SHIFT command removes one argument from the list of
# command line arguments.
Shift
Shift
# $* contains now all the files:
for file in $*; Do
If [-F "$file"]; Then
Newfile= ' echo ' $file | Sed "s/${old}/${new}/g" '
If [-F "$newfile"]; Then
echo "ERROR: $newfile exists already"
+ Else
echo "Renaming $file to $newfile"
-MV "$file" "$newfile"
Fi
-Fi
Done


From the beginning, we have explained in the previous two lines that there are new content starting from the third line. If statements are similar to other programming languages, they are process control statements. Its syntax is:

If ...; Then

...

Elif ...; Then

...

Else

...

Fi

Unlike other languages, the conditional portions of the IF statement in a Shell script are separated by semicolons. The [] in the third row represents the condition test, and the commonly used condition tests are as follows:

[-F "$file"] determine if $file is a file

[$a-lt 3] Determines whether the value of $ A is less than 3, and the same-gt and-le represent greater than or less than or equal to

[-X $file] Determines whether the $file exists and has executable permissions, and the same-R test file readability

[-N "$a"] determine if the variable $ A has a value, test the empty string with-Z

["$a" = "$b"] determine whether the value of $ A and $b are equal

[Cond1-a Cond2] to determine whether Cond1 and Cond2 are also established,-o means cond1 and Cond2 have a set up

Be aware of the spaces in the Condition Test section. there are spaces on both sides of the square brackets, and there are also spaces on both sides of the-F,-lt, =, and so on. Without these spaces, the shell will make an error when interpreting the script.

The number of command-line arguments, including $ #表示包括 $ . In the shell, the script name itself is $, and the remainder is $, $, $ ..., ${10}, ${11}, and so on. $* represents the entire list of parameters, excluding$ A, which means that the parameter list for the file name is not included.

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

Exit 12th is the Linux command that exits the current process. All Linux commands, such as Cat and exit above, can be used in shell scripts, and on the one hand, skilled use of Linux commands can greatly reduce the length of shell scripts.

14, 62 Sentences are assignment statements, respectively, the first and second parameters are assigned to the variable old and new. The next two sentences are comments, note that the following two shift function is to delete the first and second parameters in the parameter list, followed by the new first and second parameters, note that the parameter list is not included in the original.

Then, from 21 rows to 31 rows is a loop statement. The loops in Shell script are in the following formats:

While [Cond1] && {| |} [Cond2] ...; Do

...

Done

for Var in ...; Do

...

Done

for ((COND1; cond2; cond3)) do

...

Done

Until [Cond1] && {| |} [Cond2] ...; Do

...

Done

In these loops, you can also interrupt the current loop operation using the break and continue statements in the C language. The Loop in line 21st places the parameters 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, use the SED command to search for and generate a new file name. Sed can basically be seen as a find-and-replace program that reads text from standard inputs, such as pipelines, and outputs the results to standard output, and SED uses regular expressions to search. In line 23rd, Backtick (') takes out the output of a command between two Backtick, where the result is assigned to the variable newfile. After that, judge whether NewFile already exists, or change file to NewFile. This way we understand what this script does, and the other scripts written by Shell script are similar, except that the syntax and usage are slightly different.

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

First, in addition to the IF statement, the Shell script also has a case statement similar to the multi-branched structure in C, which has the following syntax:

Case Var in

Pattern 1)

... ;;

Pattern 2)

... ;;

*)

... ;;

Esac


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

While Getopts vc:option

Do

Case $OPTION in

c) copies= $OPTARG

Ehco "$COPIES";;

V) echo "Suyang";;

\?) Exit 1;;

Esac

Done

The above getopts is similar to the function getopts provided by the C language, and in shell script, getopts is often used in conjunction 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, then it will be the character after the hyphen and option_string to compare, if the match succeeds, the value of the variable variable is set to this option, if no match, Then set the value of the variable to?. Sometimes, the option also takes a value, such as-C5, to add a colon after the option letter in option_string, getopts the colon, reads the value, and puts the value in the special variable Optarg. This command is more complex and, if necessary, can be read in detail by the shell-related material.

The function of the above loop is to take out the option followed by the script name, to process it, and if you enter an illegal option, go to the "? Specified section and exit the script."

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

Select Var in ...; Do

Break

Done

For example, the output of the following program is:

#!/bin/bash

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, which has the following grammatical form:

functionname ()

{

...

}

For example, we can put in the second example above the fourth to 12th row in a named help function body, the next time each call to write help directly. The method for handling function invocation parameters in a function is to represent the first and second parameters, using $*, as the argument list, directly using the above mentioned above.

We can also debug shell script scripts under the shell, but the simplest way is to use the echo output to see the variable values. Bash also provides a true debugging method, which is to use the-x parameter when executing a script.

Sh? x filename.sh

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

Getting Started with Linux shell programming

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.