#! /bin/bash
# testing the exit status of a function
#
function func1 {
echo "This is the first form of defining a function:"
ls -l badfile # badfile is not exist
}
func2() {
echo "This is the second form of defining a function:"
date #
}
echo "Testing the function and exit status"
echo
func1
echo "The exit status of func1 is: $?"
echo
func2
echo "The exit status of func2 is: $?"
[iyunv@benxintuzi shell]# ./35.sh
Testing the function and exit status
This is the first form of defining a function:
ls: cannot access badfile: No such file or directory
The exit status of func1 is: 2
This is the second form of defining a function:
Tue Aug 11 22:43:48 PDT 2015
The exit status of func2 is: 0
2 使用return命令可以返回0~255之间的任意值
#! /bin/bash
# testing the exit status of a function
#
func() {
read -p "Please enter a value: " value
echo "doubling the input value..."
return $[ $value * 2 ]
}
func
echo "The exit status of func is: $?"
[iyunv@benxintuzi shell]# ./36.sh
Please enter a value: 50
doubling the input value...
The exit status of func is: 100
[iyunv@benxintuzi shell]# ./36.sh
Please enter a value: 200
doubling the input value...
The exit status of func is: 144
3 使用变量保存,这种方式不仅可以返回任意数值,还可以返回字符串值
#! /bin/bash
# testing the exit status of a function
#
func() {
read -p "Please enter a value: " value
echo $[ $value * 2 ]
echo "hello, I come"
}
result=`func`
echo "The exit status of func is: $result"
[iyunv@benxintuzi shell]# ./37.sh
Please enter a value: 500
The exit status of func is: 1000
hello, I come
3 函数参数
函数可以利用标准的环境变量参数,$0表示函数名,$1表示第一个参数,$2表示第二个参数,...,$#表示参数个数。
#! /bin/bash
# access script parameters inside a function
#
func() {
echo $[ $1 * $2 ]
}
if [ $# -eq 2 ]
then
value=`func $1 $2`
echo "The result is $value"
else
echo "Usage: func a b"
fi
[iyunv@benxintuzi shell]# ./38.sh 55 66
The result is 3630
#! /bin/bash
# array variable to function
func() {
local newarray newarray=(`echo "$@"`) echo "The new array value is: ${newarray
}"
local sum=0
for value in ${newarray
}
do
sum=$[ $sum + $value ]
done
echo "The sum of newarray is: $sum"
}
myarray=(1 2 3 4 5)
echo "The original array is ${myarray
}"
func ${myarray
} [iyunv@benxintuzi shell]# ./41.sh
The original array is 1 2 3 4 5
The new array value is: 1 2 3 4 5
The sum of newarray is: 15
数组作为函数返回值:
#! /bin/bash
# function return array
func() {
local oriarray
local newarray
local elements
local i
oriarray=(`echo "$@"`)
newarray=(`echo "$@"`)
elements=$[ $# - 1 ]
for (( i = 0; i <= $elements; i++ ))
{
newarray[$i]=$[ ${oriarray[$i]} * 2 ]
} echo ${newarray[*]}
}
myarray=(1 2 3 4 5)
echo "The original array is ${myarray
}"
arg1=`echo ${myarray
}`
result=(`func $arg1`)
echo "The new array is: ${result
}"
[iyunv@benxintuzi shell]# ./42.sh
The original array is 1 2 3 4 5
The new array is: 2 4 6 8 10