shell的函數和Javacript和php的函數聲明一樣,只不過shell在調用函數的時候,只需要寫函數名就可以調用函數,注意不要在函數名后面加括號
創建並使用函數
#!/bin/bash
#文件名:test.sh
function test(){
echo "aaaaaaa"
}
#直接使用函數名就可以調用函數
test
test
運行:
ubuntu@ubuntu:~$ ./test.sh aaaaaaa aaaaaaa ubuntu@ubuntu:~$
函數傳參、局部變量
給函數傳遞參數的方法 和給運行腳本傳參數的方法相同:寫在調用的函數名后面,空格分隔。
使用$1表示第一個參數,$#獲取所有參數的個數,$*獲取所有參數
shell中,默認在腳本任何地方定義的變量都是全局變量,但是可以再函數中使用local限定為局部變量,只在本函數中有效。
#!/bin/bash
#文件名:test.sh
#求0到num的和
function sum(){
local num=$1
local tot=0
local i=0
while [ $i -le $num ];do
tot=$[ $tot + $i ]
i=$[ $i + 1 ]
done
echo $tot
}
res=$(sum 100)
echo "0+1+2+...+100="$res
運行:
ubuntu@ubuntu:~$ ./test.sh 0+1+2+...+100=5050 ubuntu@ubuntu:~$
給函數傳遞數組(在函數中復制數組)
使用的是$*訪問傳遞的所有數組元素,所以在傳遞給函數數組時,不要只寫數組名,應該寫為${arr[*]}才是將數組所有元素傳遞。
在函數內部使用()將$*括起來,此時就類似於將數組元素展開到()中,然后賦值給一個變量。
#!/bin/bash
arr=("one" "two" "three")
function show(){
#create a new array
local arr=($*)
arr[0]="opq";arr[1]="rst";arr[2]="xyz"
echo ${arr[*]} ${#arr[*]}
}
echo ${arr[*]} ${#arr[*]}
show ${arr[*]}
echo ${arr[*]} ${#arr[*]}
運行結果:
ubuntu@ubuntu:~$ ./test.sh one two three 3 opq rst xyz 3 one two three 3
函數返回數組
#!/bin/bash
function return_arr(){
local arr=("one" "two" "three")
echo ${arr[*]}
}
#注意格式,是在返回值的外邊加一層括號
res=($(return_arr))
echo ${#res} ${res[*]}
