Shell函数和数组

函数的返回值用return,脚本的返回值用exit

shell函数只允许返回数字,若不是则报line 6: return: num: numeric argument required;若是写了return,则返回return语句后跟的数值,若是没有return语句则返回最后一个命令的执行结果

Shell函数的书写规范
function name { commands } == name () { commands } #创建函数
推荐的书写函数的方法(带括号)
function 函数名() {
指令集...
return n
}
简化写法:
函数名() {
指令集...
return n
}
不推荐使用下面的方法(无括号,函数名和左大括号之间要有空格。)
function 函数名 {
指令集...
return n
}

[root@web01 scripts]# cat fun1.sh
#!/bin/bash
function fun(){
local i=var    #定义局部变量,只能在函数中使用
echo "I am $i."
echo "I like linux."
}
fun

[root@web01 scripts]#sh fun1.sh oldgril    #把脚本外的参数传给函数,运行结果为I am oldgril
#!/bin/bash
function fun(){
local i=$1
echo "I am $i."
}
fun $1

[root@web01 scripts]# cat check_url1.sh    #URL检测脚本
#!/bin/bash
. /etc/init.d/functions     #调用系统函数
function usage(){
echo "usage:$0 URL"
exit 1
}
function check_url(){
wget -q --spider -T 10 $1 &>/dev/null
if [ $? -eq 0 ]
then
action "$1 is ok" /bin/true
else
action "$1 is no" /bin/false
fi
}
function main(){
if [ $# -ne 1 ]
then
usage
else
check_url $1
fi
}
main $*

数组
[root@web01 ~]# array[3]=3   #给数组赋值([3]为数组下标)
[root@web01 scripts]# echo ${array[3]} #打印给数组赋的值
3
[root@web01 scripts]# array=(1 2 3) #静态数组设置
[root@web01 scripts]# echo ${array[0]} #[0]为数组元素的下标,默认为从0开始
1
[root@web01 scripts]# echo ${array[1]}
2
[root@web01 scripts]# echo ${array[2]}
3
[root@web01 scripts]# echo ${array[*]} 或 echo ${array[@]} #打印所有元素
1 2 3
[root@web01 scripts]# echo ${#array[@]} 或 echo ${#array[*]} #打印数组长度
3
[root@web01 scripts]# array=($(ls)) 或 array=(`ls`) #命令结果放入数组(动态数组)
[root@web01 scripts]# cat arr2.sh #用for循环打印数组内容
#!/bin/sh
array=(1 2 3 4)
for((i=0;i<${#array[*]};i++))
do
echo ${array[$i]}
done
echo ======================
for n in ${array[*]}
do
echo $n
done

 

posted @ 2017-12-14 15:55  風£飛  阅读(374)  评论(0编辑  收藏  举报