Shell scripts syntax

Source: Internet
Author: User
Tags case statement vars

Shell scripts are similar to the C language and also have a fixed language format. in short, shell scripts are like batch processing files (. BAT), the most basic function is to write a lot of commands together, so that users can easily execute a file shell script and execute multiple commands at a time.

 

(1) Format of the first line of shell script

#! /Bin/sh

Symbol #! Specifies the parsing program of the script file. The sh parser in the bin directory is used here. after the script is edited, if you want to execute the script, you must make it executable, that is:

Chmod + x filename

In this way, the shell script can be executed. If the shell script does not have the execution permission, as shown in

Chmod-x filename

When the script is run, the system prompts Bash:./Hello. sh: Permission denied.

 

(2) Comments in Shell

During shell programming, the sentence starting with # represents comments until the end of this line. if a comment is used, even if the script is not used for a long time, the role and working principle of the script can be understood in a short time.

 

(3) commands that interrupt shell scripts

You can use the exit command to interrupt the program and return a value to the system.

For example:

#! /Bin/bash

Echo "Hello embeded! /N"

Exit 0

The system prints "Hello embeded! "Newline. When exit 0 is executed, the script is left and 0 is returned to the system.

 

(4) command for executing shell scripts

For example, the shell script name is hello. Sh.

<1> execution Method 1: #./Hello. Sh

<2> execution Method 2: # sh hello. Sh

 

(5) variables in Shell

In shell scripts, there are two types of variables: User-Defined variables and system default variables.

1. User-Defined variables

In shell programming, all variables are composed of strings and do not need to be declared in advance, that is, the type of the variable is not declared in advance, such as S1, in shell programming, the only supported type of variable is string.

Example 1:

Shell script: mythirdscript. Sh

#! /Bin/sh

Num = 2

Echo "this is the $ numnd"

Execution result:

[Root @ localhost lishuai] #./mythirdscript. Sh

This is

The execution result does not print "this is the 2nd". You can use curly brackets to tell shell that you need to print the value of the variable num.

For example, Echo "this is the $ {num} Nd"

Execution result:

This is the 2nd

Example 2: Numeric operation

#/Bin/bash

Echo "input your first number"

Read num1

Echo "input your second number"

Read num2

Total = $ ($ num1 * $ num2 ))

Echo "Total = $ total"

Note: Var = $ () # Two parentheses or declare-I var. This declares that VaR is an integer.

Attention !!!

<1> when a custom variable is assigned a value, no space is allowed between the left and right sides of "=.

<2> the end of a bash statement does not require a semicolon.

<3> If the variable content is determined by the user, you can use the "read" command to obtain the user input value from the terminal keyboard.

For example: # Read-P "Please input your name" Name

In this way, the content entered by the user is saved in the variable name.

2. Default System Variables

<1> $ # Number of command line parameters for input script

<2> $ * all command line parameter values, with spaces left between each parameter value

<3> $0 command itself (shell file name)

<4> $1 First Command Line Parameter

<5> $2 second command line parameter

Shell script: myforthscript. Sh

#! /Bin/sh

Echo "Number of vars:" $ #

Echo "values of vars:" $ *

[-N "$ S1"] & Echo "value of var1:" $1

[-N "$ S2"] & Echo "value of var2:" $2

[-N "$ S3"] & Echo "value of var3:" $3

[-N "$ S4"] & Echo "value of var4:" $4

Execution result:

[Root @ localhost lishuai] #./myforthscript. Sh 1 2 3 4

Number of vars: 4

Values of vars: 1 2 3 4

Value of var1: 1

Value of var2: 2

Value of var3: 3

Value of var4: 4

Attention !!!

Local variables of shell scripts

In C, local variables are included. In shell scripts, local variables are also included. You can declare a local variable by adding the local keyword when the variable is assigned for the first time.

Shell script: mydomainthscript. Sh

#! /Bin/sh

Hello = "var1"

Echo $ hello

Function func1 # Use the keyword function to define a function named func1

{

Local Hello = "var2"

Echo $ hello

}

Func1

Echo $ hello

Execution result:

[Root @ localhost lishuai] #./mydomainthscript. Sh

Var1

Var2

Var1

If the keyword local in function func1 is removed, the execution result is:

Var1

Var2

Var2

 

(6) Shell judgment Conditions

In shell scripts, you can use the test command to check certain files or related attributes on the system. For example, to check whether/home/lishuai exists, you can write a script or command like this.

#! /Bin/bash

Test-E/home/lishuai & Echo "exit" | echo "not exit"

1. the symbol "&" is followed by the condition judgment statement, indicating that if the condition is true, the statement following "&" is executed.

2. the symbol "|" follows the condition judgment statement, indicating that if the condition is false, the statement following "|" is executed.

Test flag in Shell

(1) Check (whether or not) the "type" of a file name, such as test-e filename

<1>-e whether the file name exists

<2>-F whether the file is a normal file (-)

<3>-D whether the file is a directory (d)

<4>-B. Whether the file is a block Device File

<5>-C: whether the file is a character Device File

<6>-L whether the file is a linked file

In Linux, "-" indicates a common file, "D" indicates a directory file, and "C" indicates a device file.

(2) File Permission detection, such as test-r filename

<1>-r checks whether the file name has the "readable" permission on the current user.

<2>-W checks whether the file name has the "writable" permission on the current user.

<3>-x checks whether the file name has the "executable" permission on the current user.

<4>-s file size is not 0

(3) Judgment between two integers, such as test N1-EQ N2

Comparison operation Integer Operation string operation

Same-eq =

Different-ne! =

Greater than-GT>

Less than-lt>

Greater than or equal to-Ge

Less than or equal to-le

Blank-z

Not empty-n

Routine:

Compare whether integers A and B are equal if [$ A = $ B] (EQ is also available)

Judge whether integer A is greater than integer B if [$ A-GT $ B]

Compare whether strings A and B are equal if [$ A = $ B]

Judge whether string a is null if [-Z $ A]

Judge whether integer A is greater than B if [$ A-GT $ B]

(4) Multi-condition judgment, such as test-r filename-a-x filename

<1>-A both conditions are true. For example, test-r file-a-X file, true is returned if file has both R and X permissions.

<2> if either of the-O conditions is true, for example, test-r file-o-x file, true is returned if file has R or X permissions.

<3>! Condition inversion, such as test! -X file, true is returned if file does not have X permission

 

(7) Judgment symbol []

In addition to test, you can also use the [] Judgment symbol to judge data. the usage of brackets [] is almost the same as that of test, except that brackets are used to determine the statement if... then... fi.

Attention !!!

In the Judgment symbol [], each component must be separated by spaces, for example:

# Name = "lishuai"

# ["$ Name" = "lishuai"]

1. there is a space between the left and right sides of the first square brackets, and a space between the left and right sides of the second square brackets, there is also a space between the symbol "=" and the components on both sides.

2. Double quotation marks are recommended for variables in brackets.

3. Double quotation marks or single quotation marks are recommended for constants in brackets.

4. In shell script language, "=" is used to determine the logical expression, which is "Compare"; "=" is used to set the variable content, which is "set ".

 

(8) condition judgment (if... then... Statement)

Attention !!!

In shell scripts, & and | have different meanings.

(1) & represents and

(2) | indicates or

Conditional judgment if... then... the statement is a logic control language in shell script language. It has three common statements:

(1) first format: similar to the IF statement in C language, only one Fi is required to indicate the end of the IF statement.

If [conditional judgment Expression]; then

# Commands that can be executed when the conditional judgment Expression is set

Fi

(2) second format: similar to the IF... else statement in C language, only one Fi is required to indicate the end of the IF statement.

If [conditional expression]; then

# Commands that can be executed when the conditional judgment Expression is set

Else

# Commands that can be executed when the conditional judgment Expression is invalid

Fi

(3) third format: similar to the C language if... else...

If [conditional expression 1]; then

# Commands that can be executed when condition expression 1 is set

Elif [conditional expression 2]; then

# Commands that can be executed when condition expression 2 is set

Else

# Commands that can be executed when both conditional expressions 1 and 2 are invalid

Fi

 

(9) condition judgment (case... esac Statement)

This condition is similar to the switch... case... statement in C language. Its format is:

Case $ variable name in

"First variable content ")

Program Section

;;

"Second variable content ")

Program Section

;;

*)

Other Program Execution segments that do not contain the first variable content or the second variable content

Exit 1

;;

Esac

Attenton !!!

(1) The case statement must end with esac.

(2) The last two semicolons are required to indicate the end of each variable.

(3) The final "*" function is similar to default in C.

 

(10) Application of functions in Shell

Functions can simplify a lot of program code in shell scripts. in shell scripts, the function must be defined before calling, and must be defined at the beginning of the program so that available program segments can be found during execution. it has a fixed Definition Format:

Function Name (){

Program Section

}

Attention !!!

The braces on both sides of the function cannot be in the same line.

 

(11) loop (while... do... done, until... do... done)

The difference between the two loops: When the while clause is true, the until clause is false.

(1) loop while... do... done format

When the condition is set, a loop is executed until the condition is not set.

While [condition]

Do

Program Section

Done

(2) Format of loop until... do... Done

Terminate the loop when the condition is set. Otherwise, the loop is executed continuously.

Until [condition]

Do

Program Section

Done

 

(12) loop (for... do... done)

The for loop structure is different from the C language. In bash, The for loop has two basic structures:

Basic Structure 1:

For (initial value; Restriction value; execution step ))

Do

Program Section

Done

Attention !!!

<1> This method is mainly used for numerical operations.

<2> as shown in the preceding for format, each component is separated by spaces. In fact, these spaces are not required, but we recommend that you use them.

 

Basic Structure 2:

For VaR in con1 con2 con3...

Do

Program Section

Done

Attention !!!

<1> $ VaR is a loop control variable. [LIST] is a set to be traversed by var. The do/done pair contains the loop body, which is equivalent to a pair of braces in C. in addition, if do and for are written in the same line, you must add ";",

For example, for $ VaR in [LIST]; do

<2> for loop statement execution process:

Assign each value in [LIST] to the variable $ var, and then execute the operation of the program segment.

For 1st cycles, the content of $ VaR is con1.

For 2nd cycles, the content of $ VaR is con2.

For 3rd cycles, the content of $ VaR is con3.

4th cycles ,......

<3> note that the variable day in the for row does not contain the "$" symbol. in the loop body, the variable day in the ECHO row must contain the "$" symbol. this is because the row where for is located is a value assignment to the variable day, not a reference. in Linux, the "$" symbol is added only when variables are referenced.

 

(13) tracking and debugging shell scripts

The script may cause problems before it is executed. If the script is provided in Linux, you do not need to directly execute the script to determine whether there is a problem.

[Root @ localhost lishuai] # sh [-nvx] scripts. Sh

Parameters:

-N: Check the syntax only when no script is executed.

-V output the script content to the screen before executing the script

-X displays the script content on the screen. this parameter is most useful.

For example, there is a script file test. Sh, Which is afraid of problems before running the script. You can use the methods provided by Linux to check whether the script is faulty.

[Root @ localhost lishuai] # sh-X test. Sh

The-x parameter can list all program segments to be executed before execution. If it is a program segment, the "+" symbol is added at the beginning of the output to indicate that it is a program segment.

Attention !!!

There are a large number of script files in Linux. If the script is not available, you can use the vim editor to open the script file and use the system description to understand it.

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.