標籤:shell數組 shell函數 shell遍曆數組
5.1 函數
格式:
func() { command}
樣本1:
#!/bin/bashfunc() { echo "This is a function."}func# bash test.shThis is a function.
Shell函數很簡單,函數名後跟雙括弧,再跟雙大括弧。通過函數名直接調用,不加小括弧。
樣本2:函數傳回值
#!/bin/bashfunc() { VAR=$((1+1)) return $VAR echo "This is a function."}funcecho $?# bash test.sh2
return在函數中是定義狀態傳回值,返回並終止函數,但返回的只能是數字,類似於exit 0。
樣本3:函數傳參
#!/bin/bashfunc() { echo "Hello $1"}func world# bash test.shHello world
通過Shell位置參數給函數傳參。
部落格地址:http://lizhenliang.blog.51cto.com
QQ群:Shell/Python營運開發群 323779636
5.2 數組
數組是相同類型的元素按一定順序排列的集合。
格式:
array=(元素1 元素2 元素3 ...)
用小括弧初始化數組,元素之間用空格分隔。
定義方法1:初始化數組array=(a b c)定義方法2:建立數組並添加元素array[下標]=元素定義方法3:將命令輸出作為數組元素array=($(command))
數組操作:
擷取所有元素# echo ${array[*]} # *和@ 都是代表所有元素a b c擷取數組長度# echo ${#array[*]}3擷取第一個元素# echo ${array[0]}a擷取第二個元素# echo ${array[1]}b擷取第三個元素# echo ${array[2]}c添加元素# array[3]=d# echo ${array[*]}a b c d添加多個元素# array+=(e f g)# echo ${array[*]}a b c d e f g刪除a元素# unset array[a] # 用名字刪除會保留元素下標# echo ${array[*]}b c d e f g刪除第一個元素# unset array[1] # echo ${array[*]}c d e f g
數組下標是以0開始。
樣本1:講seq產生的數字序列迴圈放到數組裡面
#!/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刪除數組# unset array
樣本2:遍曆數組元素
#!/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
本文出自 “李振良的技術部落格” 部落格,請務必保留此出處http://lizhenliang.blog.51cto.com/7876557/1882962
第五章 Shell函數與數組