Shell函数和数组
函数的返回值用return,脚本的返回值用exit
shell函数只允许返回数字,若不是则报line 6: return: num: numeric argument required;若是写了return,则返回return语句后跟的数值,若是没有return语句则返回最后一个命令的执行结果
1、函数的书写规范
function name { commands } == name () { commands }    # 创建函数
推荐的书写函数的方法(带括号)
function 函数名() { 指令集... return n }
简化写法:
函数名() {
    指令集...
    return n
}
不推荐使用下面的方法(无括号,函数名和左大括号之间要有空格。)
function 函数名 { 指令集... return n }
[root@web01 scripts]# cat fun1.sh
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 $*
2、数组
[root@web01 ~]# array=(hello world '!!!')                               # 设置静态数组
[root@web01 ~]# echo ${!array[@]}                                       # 获取数组中元素的有效下标
0 1 2
[root@web01 ~]# echo ${array[0]}                                          # [0]为数组元素的下标,默认为从0开始
hello
[root@web01 ~]# echo ${array[1]}
world
[root@web01 ~]# echo ${array[*]}  或  echo ${array[@]}          # 打印所有元素
hello world !!!
[root@web01 ~]# echo ${#array[@]}  或  echo ${#array[*]}      # 打印数组长度
3
[root@web01 ~]# array[3]=shell                                              # 向数组中追加元素
[root@web01 ~]# echo ${array[3]}                                          # 打印给数组赋的值
shell
[root@web01 ~]# array=($(ls))  或   array=(`ls`)      # 命令结果放入数组(动态数组)
[root@web01 ~]# cat arr.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 echo ====================== for m in "${!array[@]}"; do echo "${array[$m]}" done
 
                    
                 
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号