注意點:
1、函數名必須是唯一的
2、如果重定義了函數,新定義會覆蓋原來函數的定義
一、定義函數的方式
方法1、
function name {
commands
}
方法2、
name() {
commands
}
二、使用函數輸出
function dbl {
read -p "Enter a value: " value
echo $value
#echo $[ $value * 2 ]
}
result=$(dbl)
echo "The new value is $result"
read -p "Enter a value: " value
echo $value
#echo $[ $value * 2 ]
}
result=$(dbl)
echo "The new value is $result"
三、在函數傳遞參數
方法1:傳遞一個
要在函數中使用參數值,必須在調用函數時手動將它們傳過去
$ cat test
#!/bin/bash
# trying to access script parameters inside a function
function func7 {
echo $[ $1 * $2 ]
}
if [ $# -eq 2 ]
then
value=$(func7 $1 $2)
echo "The result is $value"
else
echo "Usage: badtest1 a b"
fi
方法2:傳遞數組
1 #!/bin/bash
2 function testit {
3 local newarray
4 newarray=($(echo "$@"))
5 echo "The new array value is: ${newarray[*]}"
6 }
7 myarray=(1 2 3 4 5)
8 echo "The original array is ${myarray[*]}"
9 testit ${myarray[*]}
2 function testit {
3 local newarray
4 newarray=($(echo "$@"))
5 echo "The new array value is: ${newarray[*]}"
6 }
7 myarray=(1 2 3 4 5)
8 echo "The original array is ${myarray[*]}"
9 testit ${myarray[*]}
[Linux_test]$ ./aaa.sh
The original array is 1 2 3 4 5
The new array value is: 1 2 3 4 5
The original array is 1 2 3 4 5
The new array value is: 1 2 3 4 5
四、從函數返回數組
#!/bin/bash
function arraydblr {
#local 用來聲明局部變量
local origarray
local newarray
local elements
local i
origarray=($(echo "$@"))
newarray=($(echo "$@"))
elements=$[ $# - 1 ]
for (( i = 0; i <= $elements; i++ ))
{
newarray[$i]=$[ ${origarray[$i]} * 2 ]
}
echo ${newarray[*]}
}
myarray=(1 2 3 4 5)
echo "The original array is: ${myarray[*]}"
arg1=$(echo ${myarray[*]})
result=($(arraydblr $arg1))
echo "The new array is: ${result[*]}"
五、遞歸函數
function fact{
if [ $1 -eq 1 ]
then
echo 1
else:
local temp=$[ $1 - 1 ]
local result=$(factorial $temp)
echo $[ $result * $1 ]
fi
}
result=$(factorial $value)
六、函數庫文件
使用函數庫的關鍵在於source命令。source命令會在當前shell上下文中執行命令,而不是創建一個新shell。可以用source命令來在shell腳本中運行庫文件腳本。這樣腳本就可以使用庫中的函數了。
source命令有個快捷的別名,稱作點操作符(dot operator)。要在shell腳本中運行myfuncs庫文件,只需添加下面這行:
. ./myfuncs
Example:
#!/bin/bash
# using functions defined in a library file
. ./myfuncs
value1=10
value2=5
result1=$(addem $value1 $value2)
result2=$(multem $value1 $value2)
echo "The result of adding them is: $result1"
echo "The result of multiplying them is: $result2"
也可以參考Home目錄下的 .bashrc 文件