Introduction to Linux Shell Programming

Source: Internet
Author: User
Tags case statement

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 by the subsequent path is the shell program that explains 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, you can 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.

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<<HELP 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' *.HTM10 11 HELP12      exit 013 fi14 OLD="$1"15 NEW="$2"16 # The shift command removes one argument from the list of17 # command line arguments.18 shift19 shift20 # $* contains now all the files:21 for file in $*; do22 if [ -f "$file" ]; then23     newfile=`echo "$file" | sed  "s/${OLD}/${NEW}/g"`24         if [ -f "$newfile" ]; then25             echo "ERROR: $newfile exists already"26         else27             echo "renaming $file to $newfile "28             mv "$file" "$newfile"29         fi30 fi31 done

 

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:

 
   1:  if …; then 
   2:  …
   3:  elif …; then… 
   4:  else… 
   5:  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 starts with <, followed by a string. This string also appears at the end of the here document, indicating that the document ends. 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.

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…donefor var in …; do…donefor (( cond1; cond2; cond3 )) do…doneuntil [ 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, case statement

The case statement is applicable to applications that require multiple branches.

The format of the case Branch statement is as follows:

CaseVariable nameIn

Mode 1)

Command sequence 1

;;

Mode 2)

Command Sequence 2

;; 

*)

Default command sequence

Esac 

The case statement structure has the following features:

The end of a case line must be the word "in", and each pattern must end with a right brace.

Double Semicolon";;"Indicates that the command sequence ends.

In the matching mode, square brackets are used to indicate a continuous range, for example, [0-9]. vertical bars are used to represent or.

The last "*)" indicates the default mode. When the previous modes cannot match the variable, the system will execute "*)"

Command sequence.

 

Case statement example: the user enters a character from the keyboard and determines whether the character is a letter, number, or other character,

And output the corresponding prompt information.

 1 #!/bin/bash 2 read -p "press some key ,then press return :" KEY 3 case $KEY in 4 [a-z]|[A-Z]) 5 echo "It's a letter." 6 ;; 7 [0-9])  8 echo "It's a digit." 9 ;;10 *)11 echo "It's function keys、Spacebar or other ksys."12 esac

 

 

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/bashecho "Your choice?"select var in "a" "b" "c"; dobreakdoneecho $var----------------------------Your choice?1) a2) b3) 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.

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.