1.函数的定义和语法
函数由两部分组成:函数名和函数体
语法一:
f_name (){
...函数体...
}
语法二:
function f_name {
...函数体...
}
语法三:
function f_name () {
...函数体...
}
2.函数调用
调用:函数只有被调用才会执行
调用:给定函数名
函数名出现的地方,会被自动替换为函数代码
函数的生命周期:被调用时创建,返回时终止
3.函数返回值
函数有两种返回值:
函数的执行结果返回值:
(1) 使用echo等命令进行输出
(2) 函数体中调用命令的输出结果
函数的退出状态码:
(1) 函数的返回值默认取决于函数中执行的最后一条命令的退出状态码,返回0或非0(0-255)
(2) 自定义退出状态码,其格式为:
return 从函数中返回,用最后状态命令决定返回值
return 0 无错误返回。
return 1-255 有错误返回
函数需要返回任意值,需要用echo
return的返回值缺陷
可自定义函数返回值,使用return
return 返回值范围0-255,只能返回数值,如果值大于255,返回值不正确。
而且无法返回浮点数,字符串。
示例1:
#!/usr/bin/bash
fun2(){
read -p "enter num:" num
let $[2*$num]
}
fun2
shell> bash fun3.sh
enter num:2
示例1,函数执行后没有任何返回值
示例2:
#!/usr/bin/bash
fun2(){
read -p "enter num:" num
let $[2*$num]
}
fun2
echo "fun2 return value: $?"
[root@localhost shell]# bash fun3.sh
enter num:2
fun2 return value: 0
示例2,函数执行后使用$?获取返回值,默认取决于函数中执行的最后一条命令的退出状态码,返回0或非0(0-255之间的数字)
示例3:
#!/usr/bin/bash
fun2(){
read -p "enter num:" num
return $[2*$num] #return后面不能使用表达式,只是数值
}
fun2
echo "fun2 return value: $?"
[root@localhost shell]# bash fun3.sh
enter num:2
fun2 return value: 4
[root@localhost shell]# bash fun3.sh
enter num:200
fun2 return value: 144 #返回结果错误,因为return返回最大值255
示例3,说明使用return返回值最大为255,超过或返回值为字符串则结果错误
示例4:
#!/usr/bin/bash
fun2(){
read -p "enter num:" num
echo $[2*$num]
}
fun2
result=`fun2` #可以使用一个变量来接收一个函数的输出
[root@localhost shell]# bash fun3.sh
enter num:200
400
示例4,使用 echo进行输出,echo可以返回任意值。
4.函数传参-位置参数
#!/usr/bin/bash
if [ $# -ne 3 ];then
echo "usage: `basename $0` par1 par2 par3"
exit
fi
fun4(){
echo "$(($1 * $2 * $3))"
}
#result=`fun4 1 2 3` #函数传参
result=`fun4 $1 $2 $3` #函数传参,关联脚本的位置传参
echo "result is: $result"
[root@localhost shell]# bash fun4.sh 1 2 3
result is: 6
可以直接给函数传参,也可以关联脚本的位置传参,上面的执行已关联脚本的位置传参。
5.函数传参-数组
#!/usr/bin/bash
num=(1 2 3 4 5)
#echo "${num[@]}"
arrary(){
factorial=1
for i in "$@" #使用$@接收所有参数
do
factorial=$[factorial * $i]
done
echo "$factorial"
}
arrary ${num[*]}
[root@localhost shell]# bash fun5.sh
120
6.函数返回-输出数组变量
示例1
#!/usr/bin/bash
num=(1 2 3)
array(){
local newarray=(`echo $*`)
local outarray=()
local i
for((i=0;i<$#;i++))
do
outarray[$i]=$(( ${newarray[$i]} * 5 ))
done
echo "${outarray[*]}"
}
result=`array ${num[*]}`
echo ${result[*]}
[root@localhost shell]# bash fun6.sh
5 10 15
示例2
#!/usr/bin/bash
num=(1 2 3)
array() {
local i
local outarray=()
# for i in $*
for i #这种模式代表传递所有参数
do
outarray[j++]=$[$i*5]
done
echo "${outarray[*]}"
}
result=`array ${num[*]}` #使用反引号会在子shell中执行
echo ${result[*]}
#函数接收位置参数 $1 $2 $3 ... $n
#函数接收数组变量 $* 或 $@
#函数使用参数的个数 $#
#函数将接收到的所有参数 赋值给新数组 newarray=($*)
[root@localhost shell]# bash fun7.sh
5 10 15
7.预定义变量说明
**预定义变量说明**
$0 脚本名
$* 所有的参数
$@ 所有的参数
$# 参数的个数
$$ 当前进程的PID
$! 上一个后台进程的PID
$? 上一个命令的返回值0表示成功