第一种定义:
function func(){ do something... }
function func { do something... }
func(){ do something... }
#!/usr/bin/env bash function func1(){ name=func1 echo "This is function $name" } func1 # 函数名与“{”之间必须有空格 function func2 { name=func2 echo "This is function $name" } func2 func3(){ name=func3 echo "This is function $name" } func3
This is function func1 This is function func2 This is function func3
function func(){ ls -l test echo "test return status code" } func echo "return status code: $?" function func(){ echo "test return status code" ls -l test } func echo "return status code: $?"
function func(){ read -p "Enter a value: " value return $[ $value * 2 ] } func echo "return status code: $?"
function func(){ name=func1 echo "This is function $name" } val1=`func` echo "The return value: $val1" val2=$(func) echo "The return value: $val2"
function func(){ arg1=$1 val=4 echo $[ $out * $arg1 * $2 ] } out=3 val1=`func $out 5` echo "The return value: $val1" val2=$(func $out 5) echo "The return value: $val2"
function func(){ local arg arg=$1 local temp=$[ $arg * 2 ] echo $temp } temp=3 val=`func 5` echo "The global temp: $temp" echo "The return value: $val"
function func(){ #local newarr=$1 只会得到数组的第一个元素 local newarr=(`echo $@`) for i in ${!myarr[*]};do newarr[i]=$[ ${newarr[i]} * 2 ] done echo "The new array: ${newarr[*]}" } myarr=(1 2 3 4 5) echo "My array: ${myarr[*]}" func ${myarr[*]}
My array: 1 2 3 4 5 The new array: 2 4 6 8 10
function func(){ local newarr=(`echo $@`) for i in ${!myarr[*]};do newarr[i]=$[ ${newarr[i]} * 2 ] done echo ${newarr[*]} } myarr=(1 2 3 4 5) echo "My array: ${myarr[*]}" val=(`func ${myarr[*]}`) echo "The return array: ${val[*]}" echo "The 5th element in the return array: ${val[4]}"
My array: 1 2 3 4 5 The return array: 2 4 6 8 10 The 5th element in the return array: 10