5.1 Functions
Format:
Func () {command}
Example 1:
#!/bin/bashfunc () {echo "This is a function."} Func# Bash Test.shthis is a function.
The shell function is simple, with the function name followed by a double parenthesis and the double curly brace. Called directly by the function name without parentheses.
Example 2: function return value
#!/bin/bashfunc () {var=$ () return $VAR echo "This is a function."} Funcecho $?# Bash TEST.SH2
Return is a function that defines the return value of a state, returns and terminates the function, but only returns a number, similar to exit 0.
Example 3: Function pass parameter
#!/bin/bashfunc () {echo "Hello $"}func world# bash Test.shhello World
Parameters are passed to the function via the shell position parameter.
Blog Address: http://lizhenliang.blog.51cto.com
QQ Group: Shell/python operation and maintenance development Group 323779636
5.2 Arrays
An array is a collection of elements of the same type arranged in a certain order.
Format:
array= (element 1 element 2 element 3 ...)
The array is initialized with parentheses, and the elements are separated by a space.
Definition Method 1: Initialize array array= (a B C) Define Method 2: Create new array and add element array[]= element definition Method 3: command output as array element array= ($ (command))
Array operations:
Get all elements # echo ${array[*]} # * and @ both represent all elements a B c get array length # echo ${#array [*]}3 get first element # echo ${array[0]}a get second element # echo ${array[1]} b Get Third element # echo ${array[2]}c add element # array[3]=d# echo ${array[*]}a b c D add multiple elements # array+= (E F g) # echo ${array[*]}a b c d E F g Delete Except for the A element # unset Array[a] # Deleted by name will retain element subscript # echo ${array[*]}b c d E F g Delete first element # unset array[1] # echo ${array[*]}c d E F g
The array subscript starts with 0.
Example 1: A sequence of number sequences generated by the SEQ is put into the array
#!/bin/bashfor i in $ (SEQ 1 10); Do array[a]= $i let A++doneecho ${array[*]}# bash TEST.SH1 2 3 4 5 6 7 8 9 10 Delete Array # unset array
Example 2: Traversing an array element
#!/bin/baship= (192.168.1.1 192.168.1.2 192.168.1.3) for ((i=0;i<${#IP [*]};i++)]; Do echo ${ip[$i]}done# bash test.sh192.168.1.1192.168.1.2192.168.1.3
This article is from the "Li Zhenliang Technology Blog" blog, make sure to keep this source http://lizhenliang.blog.51cto.com/7876557/1882962
Fifth chapter shell functions and Arrays