Linux shell scripting (ii)

Source: Internet
Author: User
Tags first string

Previous section Review

  In the previous blog post, I focused on the background of Shell scripting, how to create the first shell script in life, and the shell variables. The next step is to introduce shell programming, mainly around shell operations, process Control statements, custom functions, and script debugging.

Operator

Cases:

num1=11

Num2=22

sum= $num 1+ $num 2

Echo $sum

Format: expr m + N or $ ((m+n)) Note that there is a space between the expr operators

expr command: arithmetic operations on integer variables ( Note: There must be spaces before and after operators)

Expr 3 + 5
Expr-3–5

echo ' Expr 10/3 '

The result of 10/3 is 3, because it is the rounding
Expr 3 \* # \ is an escape character

  

Example: Calculating the value of (2 +3) x4

1. Step calculation
S= ' Expr 2 + 3 '
Expr $S \* 4

2. Complete the calculation in one step

Expr ' expr 2 +3 ' \* 4

s= ' expr \ ' expr2 + 3\ ' \* 4 '

Echo $S

Or

echo $ ((((2 + 3) * 4))

$ () the difference from ${}

The purpose of $ () is the same as the anti-quote ", which is used to indicate precedence execution.

Eg:echo $ (LS a.txt)

${} is taking the variable Eg:echo ${path}

$ (OP content) for numeric operations

eg:echo$ ((3+1*4))

Built-in test command

The built-in test command is commonly used to manipulate symbols [] to indicate that expressions are written in [], as follows:

[Expression]

Or:

Test expression

Note : There is a space between expression

eg: []; echo $?

Test scope: Integer, String, file

The result of the expression is true, then the return value of test is 0, otherwise it is not 0. when the result of an expression is true, the value of the variable $ is 0, otherwise it is not 0

String test:

Test STR1 = = STR2 tests if strings are equal

  Test STR1! = STR2 Tests if strings are not equal

  Test STR1 tests whether the string is not empty, is not empty, true,false

  Test-n str1 test string is not empty

Test-z str1 test string is empty

eg

Name=linzhiling

["$name"] && echo OK

; Command connection symbol

&& logic and conditions are met before the following statements are executed

[-Z "$name"] && echo Invalid | | Echo OK

|| Logical OR, if the condition is not satisfied, execute the following statement

Test "$name" = = "Yangmi" && Echook | | echo invalid

Integer test:

Test Int1-eq Int2 tests if integers are equal equals
Test Int1-ge Int2 tests if Int1 >=int2
Test INT1-GT Int2 tests if Int1 >int2
Test Int1-le Int2 tests if Int1 <=int2
Test Int1-lt Int2 tests if Int1 <int2
Test Int1-ne Int2 tests whether integers are not equal

eg

Test 100–GT 100

Test 100–ge 100

The following example compares the size of a two variable value:

-GT means that the greater than is greater than the meaning,-le means less equal means smaller than equals.

File test:

test-d file Specifies whether files are directories

  Test–e file files are present exists

  Test-f file Specifies whether files are regular files

  Test–l file exists and is a symbolic link

  Test-r file Specifies whether the files are readable

Test-w file Specifies whether files are writable

Test-x file Specifies whether files are executable

eg

Test-d Install.log

Test–r Install.log

Test–f Xx.log; echo $?

[-L Service.soft] && echo "is a link"

Test-l/bin/sh; echo $?

[-f/root] && echo "Yes" | | echo "No"

Multiple condition Testing:

Condition 1–a Condition 2 logic and two are true

Condition 1–o Condition 2 logical OR True if one is true

! Conditional logical non-inversion

eg

num=520

[-N "$num" –a "$num" – GE 520] && echo "Marry You" | | echo "Go on"

Age=20

Pathname=outlog

[!-d "$ pathname"] && echousable | | Echo used

Process Control Statement If/else command

1, single-spoke if condition statement

If [conditional judgment]

Then

Program

Fi

Or

If [conditional judgment]; Then

Program

Fi

Eg:#!/bin/sh

if [-X/ETC/RC.D/INIT.D/HTTPD]

Then

/ETC/RC.D/INIT.D/HTTPD restart

Fi

There are several points to note for single-branch conditional statements:

The IF statement uses the FI end, which differs from the general language using curly braces.

[Conditional judgment] is determined using the test command, so there must be a space between the brackets and the conditional judgment

Then followed by the symbol condition after the execution of the program, you can put in [] after, with ";" Split, you can also write a newline, you do not need ";".

2, Multi-branch if condition statement

If [conditional judgment 1]

Then

When the conditional judgment 1 is established, the execution of the program 1

elif [conditional judgment 2]

Then

When the conditional Judgment 2 is established, the execution of the program 2

... Omit more conditions

Else

When all conditions are not true, the final execution of this program

Fi

Example:

Read-p "Please input your name:" Name

eg

#!/bin/bash

Read-p "Please input your name:" Name

#echo $NAME

If ["$NAME" = = Root]

Then

echo "Hello ${name}, welcome!"

elif [$NAME = = Tom]

Then

echo "Hello ${name}, welcome!"

Else

echo "SB, get out here!"

Fi

Case command

The case command is a multi-branch if/else command, and the value of the case variable is used to match value1,value2,value3 and so on. The match is followed by the following command until the double semicolon is encountered (;;) The case command takes ESAC as the Terminator.

Format

cmd=$1

Case $CMD in

Start

echo "Starting"

;;

Stop)

echo "Stoping"

;;

*)

echo "Usage: {start|stop}"

Esac

For loop

The For loop command is used to execute a limited number of commands in a list entry. For example, you might loop through the same command in a list of names or lists of files. The for command is immediately followed by a custom variable, a keyword in, and a list of strings (which can be variables). When you first execute a for loop, the first string in the list of strings is assigned to the custom variable, and then the Loop command is executed until the done statement is encountered, and the second string in the string list is pushed to the custom variable, and so on until the string list is traversed.

The first type:

For N in 1 2 3

Do

Echo $N

Done

Or

For N in 1 2 3; do Echo $N; Done

Or

For N in {1..3}; do Echo $N; Done

The second type:

for ((i = 0; I <= 5; i++))

Do

echo "Welcome $i times"

Done

Or

for ((i = 0; I <= 5; i++)); Do echo "Welcome $i times"; Done

While loop

The while command determines whether to execute a while loop based on the command immediately following it, and when command executes the return value (exit status) is 0 o'clock, the while loop statement block is executed until the done statement is encountered and then returned to the while command. The return value of the command is determined, and when the return value is not 0 o'clock, the while loop is terminated.

First Kind

While expression

Do

Command

...

Done

Exercise: Ask for 1-10 squared sum of each number

The second type:

Custom functions

A function represents a set of commands or a set of functions that represents a function module, often used for modular programming.

Here are some important notes about the function:

In the shell, the function must be defined before it is called

Use return value to get the return values of the function

function is executed in the current shell, you can use the variables in the script.

The format of the function is as follows:

Function name ()

{

Command 1 .....

Command 2 ....

return value variable

}

[Function] funname [()]

{

Action

[Return int;]

}

function start ()/function Start/start ()

eg.

Attention:

If there is no () after the function name, there must be a space between the function name and {to differentiate. function return value, can only be obtained through the $? system variable, the add: return value is displayed, if not added, the result is run as the last command, as the return value. return followed by value N (0-255)

Script debugging

  Sh-x Script

  This executes the script and displays the values of all variables.

Add in shell script

  Set-x debugging part of the script

  Sh-n Script

  Not executing the script just checks the syntax of the pattern and will return all syntax errors.

Sh–v Script

Executes and displays the contents of the script.

Linux shell scripting (ii)

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.