Linux Advanced Shell Script tutorial

Source: Internet
Author: User
Tags function definition uppercase character

Shell Advanced Step

Conditional Select if statement to achieve conditional judgment

If syntax: if Commands;then commands (if the command is true, the subsequent command will be executed, fi ends;)

Elif Commands;then Commands (if the previous if is not true, then to determine whether the elif is true, the following command is true, you can write multiple elif, can be written without writing, the condition of a lot of cases to add)

else Commands;then commands (if none of the above are true, continue to determine if else is true, follow-up commands are true)

If True;then echo true;f1 (if True, execute subsequent command, end)


a condition to judge;

Case variable in

Case syntax: Case word in [mode [| mode commands] ...

Case "Variable" in

PAT1) (determine if the variable matches PAT1, then execute the following command)

Branch 1

;;

PAT2) (Execute the following command if the preceding variable does not match)

Branch 2

;;

...

*) (Match this if the variable is not preceded)

Default Branch

;;

Esac

Use the global style syntax, wildcard characters

*: Any character of any length

?: any single character

[]: Any single character within the specified range

A|b:a or B


Cycle

To run a code segment repeatedly multiple times

How many times to run repeatedly:

Number of cycles known

Number of cycles unknown

There are entry conditions and exit conditions

For,while,until


For loop

The for variable name in [Word ...]; Do Commadns; Done

Example:

For NUM in 1 2 3 4

Do

echo "Num is $num"

Done

The above digital content to write several words on the loop several times


List Generation Method:

(1) Give the list directly

(2) {} from start to finish; For example: {1..10} (1-10); {1..10..2} decrements by 2

(3) Generating a list with commands

(4) using glob, such as: *.sh

(5) variable reference: [email protected],$*


While loop

While commands (conditions entering the loop and terminating the loop);d o Commands;done (when the condition satisfies the continuation loop, the loop stops when the condition is not met)

Select loops and Menus

Select variable in list (assigns the list data to the variable and assigns the ordinal number, applies to the menu, PS3 this variable is specialized in the Select does the prompt use, $REPLY the system comes with the variable, the deposit input string)

Do

Circular Body Command

Done


Signal Capture Trap

Trap ' trigger directive ' parameter

The preceding instruction is triggered when the signal for the operation of the parameter is captured

Trap ' parameter

Ignore signal

Trap '-' parameter

Restore the original signal operation, that is, the above trap operation canceled

Trap-p

Column Custom Actions


function Introduction

More convenient code reuse, also suitable for modular programming, equivalent to Alias, alias is a command definition, and function is equivalent to a function to define multiple instructions


Defining functions

Functions consist of two parts: function name and function body

Syntax One:

F_name () {

... function Body ...

}

Syntax Two:

function F_name {

... function Body ...

}

Syntax Three:

function F_name () {

... function Body ...

}

F_name execution function

unset f_name Cancel function definition

Which terminal the defined function is to be executed at, and the other terminal cannot execute

DECLARE-F (see all defined functions)


function use (define and recall first)

Functions are generally not used in interactive environments, and are basically used in scripts

The defined function can be placed in a single file, the method of invoking the function file in the script source ' file name '

/etc/init.d/function (file for which the system specifically stores functions)

Return 10 (end current function, and $? Return value is 10, does not mean end)

Local is a special keyword that can only be used in functions; If you do not use local in the function, the variables defined in the function can be used in the shell, variables defined in the shell, functions can be called, and Local is used only in functions.

A child process cannot call a function defined in the parent process, but can use export-f f_name to convert a function to an environment function


Array

The same type of data takes a variable name, the name of the array and the subscript combination can represent the unique variable, from 0 for the first subscript, the last subscript the number of elements is n-1, the number subscript becomes a numerical index

Indexes can support custom indexes, not just numeric indexes, which are associated indexes, bash4.0 support (bash--version)


The array of Bash supports sparse format (index discontinuity)

Declaring an array:

Declare-a "Array Name"

Declare-a "Array name" (associative array; Custom index is an associative array, first declared and then called)

Array Assignment

(1) Assign only one element at a time

"Array name [index]" = "value"

(2) Assigning all elements at once

Array_name= ("VAL1" "VAL2" "VAL3")

(3) Assign only specific elements

Arraty_name= ([0]= "VAL1" [3]= "VAL2") sparse format can not be complete in this way

(4) Interactive assignment

Read-a

referencing arrays

echo ${array_name[index]} displays the index in a particular array

Referencing all elements of an array

Echo ${array_name[*]} Show all array indexes

The length of the array (the number of elements in the array)

${#ARRAY_NAME [*]}

${#ARRAY_NAME [@]}

Deletes the specified element in the array

unset Array [number]

Delete an entire array of elements

unset array


Array Data processing

To reference an element in an array:

Array slice: ${array[@]:offset:number}

Offset: Number of elements to skip

Number: How many elements to remove

The element after the offset is taken

${array[@]:offset}

Append an element to the array:

array[${#ARRAY [*]}]=value


string slices

${#变量名}: Returns the length of a string variable name

${variable name: offset}: Skip offset

${variable name: offset:number}: Skip offset take number of

${variable name:-offset}: Take the bottom three

${variable name: offset:-number}: Remove the previous offset, and then remove the number of

${variable name:-offset:-number}: Take the back offset, remove the offset to remove number, in 7


String processing

Based on pattern fetching string

${variable name #*word}: Where word can make any of the specified characters

Function: From left to right, look for variable value stored in "Variable name", match to after the character and match to the character before the character is all deleted, the question mark represents a single character;

${variable name ##*word}: Ditto, greedy mode, delete all content between the beginning of the string and the last character specified by word

${variable name%word*}: Right-to-left, finds the first occurrence of word in a variable stored string, deletes the first matching word found from right to left, and all characters from Word to the other

${variable name%%wird*}: Right-to-left, greedy mode, removes all of the characters from the beginning of the string to the last character specified by word

Find replacements

${variable/matching string/new substituted string}: Find the string represented by the variable, replace the matched string with the newly substituted string, default only replaces the first match to the

${variable//matching string/newly substituted string}: Greedy mode, replacing all strings matched to

${variable//#匹配的字符串/newly substituted string}: Replace line that begins with a matching string

${variable/% matching string/newly substituted string}: Replace line ending with matching string

${variable/matched string}: Delete matching string, non-greedy mode

${variable//matched string}: Greedy mode, delete all matching strings

${variable/#匹配的字符串}: Delete A string that begins with a matching string

${variable/% matching string}: Delete the string ending with a matching string

${variable ^ ^}: Converts the value of a variable to uppercase

${variable,}: Converts the value of a variable to lowercase


var=${str-"Expr"}; when Str has no value: var=expr; when the str value is empty: var= $str; When Str has a value: var= $str

VAR=${STR:-EXPR}; When Str has no value: var=expr; When str value is empty: var=expr; when str has value: var= $str

........


Advanced variable Usage-variable with type

Shell variables are generally untyped, but the bash shell provides declare for specifying variable types, and bash supports only integers

Declare [options] variable name

-R declares or displays read-only variables

-I declaration integer

-a defines a variable as an array

-a defines a variable as an associative array

-F Displays defined function contents

-F Displays all function names that have been defined

-X declaring environment variables and functions

-l declares variable as lowercase letter

-u declares variable as uppercase character


eval command

The eval command scans the command two times, and when the first scan checks to see if the target is a variable, the value is replaced, and the second scan executes


Indirect variable Reference

If the value of the first variable is the name of the second variable, referring to the value of the second variable from the first variable is called an indirect variable reference

The value of the variable1 is Variable2, and variable2 is the variable name, and the value of variable2 is values, and the indirect variable reference refers to the behavior of getting the value of the variable by variable1

Variable1=variable2

Variable2=value


Mktemp: Creates a temporary file and displays

mktemp [OPTION] ... [TEMPLATE]

Template:filenamexxx

x must appear at least three

OPTION:

-D: Create a temp directory

-P: Indicates the location of the directory where the temporary files reside


Install copy files

Install Command:

Install [option] source file destination file

Install [option] source target

Install [option]

Options option:

-M MODE, default permissions 755

-O OWNER: Specify owner

-G Group: Specified genus

-D Specify Directory


Expect introduction

A scenario that is primarily used to automate interactive operations by changing the interactive operation to a non-interactive operation

Expect syntax:

Expect [options] [-C command] [[[-[f|b]] cmdfile] [args]

Options:

-C: Executes the expect script from the command line, and the default expect is executed interactively

-D: Can output debug information

Related commands in expect

Spawn: Start a new process

Send: For sending a string to a process

Expect: Receiving a string from a process

Interact: Allow user interaction

Exp_continue match multiple strings after executing the action add this command


Expect most commonly used syntax (mode-action)

Single branch: Expect "HI" {send "you said Hi\n"} (Capture hi while input other does not respond)

Multi-Branch

Expect "HI" {send "you said hi\n"} \ (Discover hi print you said hi)

"hehe" {send "hehe yourself\n"} \ (Discovery hehe print hehe yourself)

"Bye" {send "Good bye\n"} (Discovery bye print Good bye)



One:

#!/usr/bin/expect

Spawn Scp/etc/fstab user @ each other IP address:/app

Expect {

"Yes/no" {send "yes\n"; Exp_continue}

"Password" {send "fang\n"}

}

Expect EOF


Two:

#!/usr/bin/expect

Spawn SSH user @ each other IP address

Expect {

"Yes/no" {send "yes\n"; Exp_continue}

"Password" {send "user password \ n"}

}

Expect EOF

Interact (execution of the above command does not exit execution of interactive commands)


Three:

#!/usr/bin/expect

Set IP "IP Address" (defines a variable named IP, with a value of the rear IP address)

Set user "username" (defines a variable named user, with a value of root)

Set Password "password"

Set Timeout 10

Spawn ssh [email protected] $ip

Expect {

"Yes/no" {send "yes\n"; Exp_continue}

"Password" {send "$password \ n"}

}

Interact


Four

#!/usr/bin/expect

Set IP [lindex $argv 0] (defines a variable named IP, the first parameter)

Set user [lindex $argv 1] (defines a variable named user, with a value of the second parameter)

Set password [lindex $argv 2] (defines a variable named password, with a value of third parameter)

Spawn ssh [email protected] $ip

Expect {

"Yes/no" {send "yes\n"; Exp_continue}

"Password" {send "$password \ n"}

}

Interact


V: Call expect in bash

#!/usr/bin/expect

#!/bin/bash

Ip=$1

User=$2

Password=$3

Expect <<eof

Set Timeout 10

Spawn ssh [email protected] $ip

Expect {

"Yes/no" {send "yes\n"; Exp_continue}

"Password" {send "$password \ n"}

}

Expect "]#" {send "Useradd hehe\n"}

Expect "]#" {send "echo magedu |passwd--stdin hehe\n"}

Expect "]#" {send "exit\n"}

Expect EOF

Eof


Linux Advanced Shell Script tutorial

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.