LinuxShell programming Entry 1-4

Source: Internet
Author: User
Introduction to LinuxShell programming (1) from the programmer's perspective, Shell itself is a program written in C language. From the user's perspective, Shell is a bridge between users and Linux operating systems. You can enter commands for execution and use Shell script programming to perform more complex operations. Today, with the increasingly sophisticated LinuxGUI, Shell programming still fails in the field of system management.

 

Introduction to Linux Shell programming (1)

 

From the programmer's perspective, Shell itself is a program written in C language. From the user's perspective, Shell is a bridge between the user and the Linux operating system. You can enter commands for execution and use Shell script programming to perform more complex operations. With the increasingly sophisticated Linux GUI, Shell programming still plays an important role in system management and other fields. A deep understanding of Shell programming is one of the required lessons for every Linux user.

Linux has many Shell types, including: Bourne Shell (/usr/bin/sh or/bin/sh) And 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 languages have different syntaxes, so they cannot be exchanged. Each Shell has its own characteristics. Basically, it is enough to master any of them. In this article, we focus on Bash, also known as Bourne Again Shell, which is widely used in daily work due to ease of use and free of charge, bash is also the default Shell for most Linux systems. In general, people do not distinguish between the Bourne Shell and the Bourne Again Shell. Therefore, in the following text, we can see #! /Bin/sh, which can also be changed #! /Bin/bash.

The format of Shell scripts written in a text editor such as vi is fixed as follows:

#! /Bin/sh

# Comments

Your commands go here

Symbol #! In the first line #! Tell the system that the program specified in 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 subsequent part is the main program. Shell scripts, like advanced languages, also have variable assignment and control statements. Except the first line, the line starting with # is the comment line until the end of this line. If a row is not completed, add/at the end of the row. This symbol indicates that the next row is merged into the same row with this row.

After editing, save the script disk as filename. sh. The file name suffix sh indicates this is a Bash script file. When executing a script, you must first change the attributes of the script file to executable:

Chmod + x filename. sh

The script execution method is as follows:

./Filename. sh

Let's start with the classic "hello world" and look at the simplest Shell script.

#! /Bin/sh

# Print hello world in the console window

A = "hello world"

Echo $

Shell Script is a weak type language. When using a variable, you do not need to declare its type first. The new variable is stored in the memory allocated in the local data zone. This variable is owned by the current Shell and cannot be accessed by any sub-process. These variables are different from the environment variables. They are stored in another memory zone called the user environment zone. The variables in this memory can be accessed by the quilt process. The variable assignment method is as follows:

Variable_name = variable_value

If a value is assigned to a variable that already has a value, the new value replaces the old value. $ Must be added before the variable name. $ variable_name can be used in quotation marks. This is obviously different from other advanced languages. In case of confusion, you can use curly brackets to distinguish them. For example:

Echo "Hi, $"

"Hi, hello worlds" is not output, but "Hi," is output ,". This is because Shell treats $ as a variable, while $ as is not assigned a value, and its value is null. The correct method is:

Echo "Hi, $ {a} s"

Variables in single quotes are not replaced.
 

Introduction to Linux Shell programming (2)

You also need to know several Linux commands related to the variables.

Env is used to display the variables and their values in the user environment zone. set is used to display the variables and their values in the local data zone and user environment zone. unset is used to delete the current value of the specified variable, this value is specified as NULL. the export command is used to transfer the variables in the local data zone to the user environment zone.

Next we will look at a more complex example. Combined with this example, we will introduce the syntax of 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' 'replace 'files...

8 EXAMPLE: rename all *. HTM files in *. html:

9 ren 'htm $ 'html' *. HTM

10

11 HELP

12 exit 0

13 fi

14 OLD = "$1"

15 NEW = "$2"

16 # The shift command removes one argument from the list

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
 

Introduction to Linux Shell programming (3)
 

 

 

From the beginning, we have explained in the previous example in the previous two rows. There is new content starting from the third line. If statements are similar to other programming languages and are process control statements. Its syntax is:

If ...; Then

...

Elif ...; Then

...

Else

...

Fi

Unlike other languages, the conditions of the if statement in Shell Script must be separated by semicolons. [] In the third row indicates a condition test. Common condition tests include the following:

[-F "$ file"] determines whether $ file is a file.

[$ A-lt 3] determines whether the value of $ a is less than 3. Similarly,-gt and-le indicate greater than or less than or equal

[-X "$ file"] checks whether $ file exists and has executable permissions. Similarly, the-r test file is readable.

[-N "$ a"] determines whether the variable $ a has a value. Use-z to test the Null String.

["$ A" = "$ B"] determines whether the values of $ a and $ B are equal.

[Cond1-a cond2] determines whether cond1 and cond2 are both valid.-o indicates that cond1 and cond2 are valid.

Note the space in the condition test section. There are spaces on both sides of square brackets and spaces on both sides of the-f,-lt, =, and other symbols. Without these spaces, an error occurs when Shell interprets the script.

$ # Indicates the number of command line parameters, including $0. In Shell, the script name itself is $0, followed by $0, $1, $2... , $ {10}, $ {11}, and so on. $ * Indicates the entire parameter list, excluding $0, that is, the parameter list excluding the file name.

Now we understand that the third line means that if the script file contains fewer than three parameters, the content between the if and fi statements will be executed. The content between lines 4 and 11th is called the Here document in Shell Script programming. The Here document is used to pass multiple lines of text to a command. The format of the Here document is < <开始,后跟一个字符串,在here文档结束的时候,这个字符串同样也要出现,表示文档结束。在本例中,here文档被输出给cat命令,也即将文档内容打印在屏幕上,起到显示帮助信息的作用。< p>

The exit command on line 3 is a Linux Command, indicating that the current process is exited. All Linux commands can be used in Shell scripts, and the cat and exit commands above can be used to greatly reduce the length of Shell scripts.

The fourteen and fifteen sentences are the value assignment statements, respectively assigning the first and second parameters to the OLD and NEW variables. The next two statements are annotations. The following two shifts are used to delete the first and second parameters in the parameter list, and the subsequent parameters are changed to the new first and second parameters in turn, note that the parameter list does not include $0.

Then, from row 21 to row 31 is a loop statement. The loop in Shell Script has 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 the above loop, you can also use a statement similar to the break and continue statements in C language to interrupt the current loop operation. The loop in the 21st line stores the parameters in the parameter list one by one in the variable file. Then enter the loop to determine whether the file is a file. If it is a file, use the sed command to search for and generate a new file name. Sed can basically be seen as a search replacement program. It reads text from standard input, such as a pipeline, and outputs the result to standard output. sed uses regular expressions for search. In row 23rd, backtick (') is used to extract the command output result between two backtick instances. Here, the result is retrieved and assigned to the variable newfile. After that, determine whether newfile already exists. Otherwise, change the file to newfile. In this way, we can understand the role of this Script. Other scripts written in Shell Script are similar, except that the syntax and usage are slightly different.

Through this example, we understand the writing rules of Shell scripts, but there are several things to be discussed.

First, in addition to the if statement, Shell Script also has a case statement similar to the multi-branch structure in C language. Its syntax is:

Case var in

Pattern 1)

... ;;

Pattern 2)

... ;;

*)

... ;;

Esac



Introduction to Linux Shell programming (4)

Let's take another example to see the usage of the case statement.

While getopts vc: OPTION

Do

Case $ OPTION

In

C) COPIES = $ OPTARG ;;

V )...;;

/?) Exit 1 ;;

Esac

Done

The above getopts is similar to the function getopts provided by C language. In Shell Script, getopts is often used together with the while statement. The getopts syntax is as follows:

Getopts option_string variable

Option_string contains a string of Single-character options. If getopts finds a hyphen in the command line parameter, it compares the character after the hyphen with option_string. If the match is successful, set the variable value to this option. If no match exists, set the variable value ?. Sometimes, the option also contains a value, such as-c5. In this case, you must add a colon to the option letter in option_string. After getopts discovers a colon, it will read the value, put the value in the special variable OPTARG. This command is complex. If necessary, you can refer to the relevant documents written in Shell.

The preceding loop is used to extract the options following the script name in sequence for processing. If an invalid option is entered, /? Exit the script program.

Second, Bash provides an extended select for interactive applications. Users can select from a group of different values. The 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)

2) B

3) c

Third, you can also use custom functions in Shell Script. The syntax format is as follows:

Functionname ()

{

...

}

For example, we can put rows 4 to 12th in the second example above into a help function. Then, we can directly write help for each call. In a function, you can use the $1 and $2 mentioned above to represent the first and second parameters respectively, and use $ * to represent the parameter list.

Fourth, we can also debug the Shell Script in Shell. Of course, the simplest way is to use echo output to view the variable values. Bash also provides a real debugging method, that is, to use the-x parameter when executing the script.

Sh? X filename. sh

This will execute the script and display the values of all variables in the script. You can also use the-n parameter. It does not execute the script, but returns all syntax errors. (N101)







 

 

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.