Linux functions and array definitions

Source: Internet
Author: User
Tags variable scope

Function Description:
Functional function is a block of statements consisting of several shell commands for code reuse and modular programming.
It is similar to the shell program, but it is not a separate process, it cannot run independently, but is part of the shell program.
A function is similar to a shell program, except that:
Shell program runs in child shell
The Shell function runs in the current shell. So in the current shell, the function can
Modify the variables in the shell

Functions consist of two parts: the function name and the function body.
Syntax One:
function F_name {
... function Body ...
}
Syntax Two:
function F_name) () {
... function Body ...
}
Syntax Three:
F_name () {
... function Body ...
}

Definition and use of functions:
? Functions can be defined in an interactive environment
? You can put a function in a script file as part of it
? Can be placed in a separate file that contains only functions
Call: function will only be executed if called
Call: Where the function name of the given function name appears, it is automatically replaced with the function code
The life cycle of a function: created when invoked, terminated on return

The function has two return values:
The return value of the function's execution result:
(1) Output using commands such as Echo
(2) output of the call command in the function body
Exit status code for the function:
(1) The default depends on the exit status code of the last command executed in the function
(2) Custom exit status code, in the form of:
Return returned from the function, with the last state command to determine the return value
return 0 returns without error.
return 1-255 has errors

A function must be defined before it is used, so the function definition should be placed at the beginning of the script until the shell first discovers it before it can be used

You can store frequently used functions in a function file and then load the function file into the shell
The file name can be arbitrarily selected, but it is best to have some kind of connection to the related task. For example
: Functions.main
Once the function file is loaded into the shell, the function can be called from the command line or script. You can use the SET command to view all defined functions whose output list includes all functions that have been loaded into the shell
To change a function, first remove the function from the shell with the unset command. After the change is complete, reload the file

The function can accept parameters:
Pass parameters to the function: When the function is called, it is separated by a white space after the function name
Given a list of parameters, for example "TestFunc arg1 arg2 ..."
In the function body, you can use $, $, ... These parameters are called;
You can use the [email protected], $*, $# and other special variables

Variable scope:
Environment variables: current shell and child shell are valid
Local variable: Only valid in the current shell process, the execution script will start
Dedicated child shell process; Therefore, local variables are scoped to the current shell script
Program files, including functions in scripts
Local variables: The life cycle of a function; The variable is automatically destroyed at the end of the function
Note: If there are local variables in the function, use local variables if their names are the same as local variables.
Methods for defining local variables in a function
Local Name=value
Environment function:
Exprot-f functions #必须先声明环境函数, again defined
View environment functions: export-f

function recursion:
function calls itself directly or indirectly
Note the number of recursive layers
Recursive instances:
Factorial is an operational symbol invented by Kiston Kaman in 1808 and is a mathematical term
The factorial (factorial) of a positive integer is all positive integers less than and equal to that number.
Number of the product, and there are 0 factorial of 1, natural number n the factorial writing n!
N!=1x2x3x...xn
Factorial can also be defined recursively: 0!=1, n!= (n-1)! Xn
N!=n (n-1) (n-2) ... 1
N (n-1)! = N (n-1) (n-2)!

Example: fact.sh

!/bin/bash

Fact () {
If [$1-eq 0-o $1-eq 1]; Then
Echo 1
Else
Echo $[$1$ (fact $[$1-1])
Fi
}
Fact $

Fork bombs:
:() {:|:&};:
Bomb () {Bomb|bomb &};bomb #原理: Recursive call to open an infinite child shell takes up memory space

Arrays:
    variables: Memory space for storing individual elements
    arrays: contiguous memory space that stores multiple elements, equivalent to
sets of multiple variables
    array names and indexes
Index: Numbering starting from 0, which is a numeric index
Note: Indexes can support the use of custom formats, not just numeric formats
, which are associated with indexes that support the
Bash array after the bash4.0 version supports sparse format (index discontinuity)
    Declaration array:
declare-a array_name
declare-a array_name:   Associative array       #关联数组必须先声明才能使用
                           ,         &NB Sp and arrays and associative arrays cannot be converted to each other
    unset Shuzu  :     Delete array
Array assignment:
  Array element assignment:
(1)   Assign only one element at a time;
Array_name[index]=value
weekdays[0]= "Sunday"
weekdays[4]= "Thursday"
(2)   Assign all elements at once:
Array_name= ("VAL1" "VAL2" "VAL3" ...)
(3)   Assign only specific elements:
array_name= ([0]= "val1″[3]=" Val2″ ...)
(4)   Interactive array value pairs assignment
Read-a array
0  1   2   3            : Each array value space Separates

Referencing an array element: ${array_name[index]}
Note: Omitting [INDEX] means referencing an element with subscript 0
The length of the array (the number of elements in the array):
${#ARRAY_NAME [
]}
${#ARRAY_NAME [@]}

File= (/var/log/*.log) #支持通配符

Arr= ({1..10}) #1到10的数组
Arr= ({a). Z})
Arr= ({a.b.c}.{ Txt,log}) #交互组合, generates six arrays

To reference an element in an array:
All elements: ${array[@]}, ${array[]}
Array slice: ${array[@]:offset:number}
Offset: Number of elements to skip
Number: How many elements to remove

All elements after the offset is taken
${array[@]:offset}
Examp:echo ${alpha[
]:3:6} #去掉前三个数值, take the back 6;
Echo ${alpha[]:-3} #从后往前取, be sure to take a space, from the back to three
echo ${alpha[
]:3:-10} #去掉前面3个和后面10个取中间 negative number can be followed by no space
Echo ${alpha[]: -4:-1} #从后取四个, then remove one from the back, leaving only three of them.

${#var}: Returns the length of the string variable var
${var:offset}: Returns the string variable var from the first offset character specifier (not
The character that includes the first offset character begins, to the last part, the offset of the
The value is between 0 and ${#var}-1 (negative values are allowed after bash4.2)
${var:offset:number}: Returns the string variable var from the first offset
character specifier (excluding the first offset character) starts with a length of
Part of Number
${var:-length}: Take the rightmost few characters of a string
Note: You must have a blank character after a colon
${var:offset:-length}: Skip the offset character from the leftmost, always right
Take to the right of the Lengh character before the distance
${var:-length:-offset}: First from the right to the left to the length of the word
To the right, and then to the rightmost offset from the right

To take a substring based on a pattern
${var#
Word}: Where Word can be any of the specified characters
Function: From left to right, find the string stored in the var variable, the first
Occurrences of Word, remove all characters from the beginning of the string to the first occurrence of Word characters
${var##Word}: Ditto, greedy mode, different is, delete the
Example:
File= "Var/log/messages"
${file#
/}: Log/messages
${file##/}: Messages

${var%word}: Where word can be any of the specified characters;
Function: From right to left, find the string stored in var variable, first
Occurrences of Word, delete the last character of the string to the left to the first occurrence of all characters between word characters;
File= "/var/log/messages"
${file%/}:/var/log
${var%%word
}: Ditto, except delete the rightmost character of the string to the left to the last occurrence of word
All characters between the characters;
Example:
Url=http://www.magedu.com:80
${url##:} 80
${url%%:
} http

Number from the go after the% from the back forward

Append an element to the array:
array[${#ARRAY [*]}]= need to append the value of the variable # because the array number is labeled as n-1, so the increased array is n

Delete an element in an array: causes sparse formatting
unset Array[index] #可以删除数字, you can delete only an element in an array

Associative arrays:
Declare-a array_name Note: You must first declare, then use
Array_name= ([idx_name1]= ' val1′[idx_name2]= ' val2 ' ...)

Find replacements
${VAR/PATTERN/SUBSTR}: Finds the string represented by Var, section
A string that is matched to by the pattern, replacing it with substr
${VAR//PATTERN/SUBSTR}: Finds the string represented by Var,
All strings that can be matched to the pattern, replaced by substr
${var/#pattern/substr}: Finds the string represented by Var,
The string to which the beginning of the line is matched by the pattern, replacing it with substr
${VAR/%PATTERN/SUBSTR}: Finds the string represented by Var,
The string to which the end of the line is matched by pattern to substr

Find and delete
${var/pattern}: Find the string represented by Var, delete the string that was first matched by pattern
${var//pattern}: All
${var/#pattern}: Beginning of the line
${var/%pattern}: End of line
Character-Case conversions
${var^^}: Converts all lowercase letters in VAR to uppercase
${var,}: Converts all uppercase letters in VAR to lowercase

Variable assignment:
${var:-value}: Returns value if Var is empty or not set, otherwise returns VAR, which can be omitted:
${var:+value}: Returns value if Var is not empty, otherwise returns a null value;
${var:=value}: If Var is empty or not set, then return value and assign value to Var, otherwise return Var
${var:?error_info}: If Var is empty or not set, then print Error_info at the current terminal, otherwise return Var

Shell variables are generally untyped, but the bash shell provides declare and
Typeset two commands are used to specify the type of the variable, and two commands are equivalent
Declare [options] variable name
-R declares or displays read-only variables
-I defines a variable as an integral number
-a defines a variable as an array
-a defines a variable as an associative array
-F Displays all function names and their contents defined before this script
-F displays only all function names defined before this script
-X declares or displays environment variables and functions
-L declares the variable to be lowercase declare–l var=upper
-U declares the variable to be uppercase Declare–u Var=lower

The eval command will first scan the command line for all permutations before executing the
Command. This command applies to variables that are not able to implement their functionality once scanned. The
command to scan a variable two times

Indirect variable references:
If the value of the first variable is the name of the second variable, the first variable is cited as a
The value of the second variable is called an indirect variable reference
The value of Variable1 is Variable2, and variable2 is the variable name,
Value of variable2, indirect variable reference refers to the behavior of getting the value of a variable by variable1
Variable1=variable2
Variable2=value

To create a temporary file:
Mktemp command: Create and display temporary files to avoid conflicts
mktemp [OPTION] ... [TEMPLATE]
TEMPLATE:filename.XXX
X must appear at least three
OPTION:
-D: Create a temp directory
-P DIR or –tmpdir=dir
Examp:mktemp–tmpdir=/testdir test. XXXXXX #直接选择全路径创建此选项可不用

Install: Similar to CP chmod CHGRP mkdir collection. Use the same as the CP command.

Install Command:
Install [OPTION] ... [-T] SOURCE DEST Single File
Install [OPTION] ... SOURCE ... DIRECTORY
Install [OPTION] ...-t DIRECTORY SOURCE ...
Install [OPTION] ...-d DIRECTORY ... Create an empty directory
Options:
-M MODE, default 755 #直接复制过去指定权限和属主属组
-O OWNER
-G GROUP

Linux functions and array definitions

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.