zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    linux文件IO操作篇 (二) 缓冲文件
    信号量和互斥锁的区别
    linux 无锁化编程
    C语言中 time相关的函数 头文件
    printf 打印字体和背景带颜色的输出的方法
    在win10环境下安装Cygwin,可以GCC编译
    学习《大话存储》
    linux内核态和用户态的信号量
    学习Makefile
    git 环境搭建
  • 原文地址:https://www.cnblogs.com/xwupiaomiao/p/8038179.html
Copyright © 2011-2022 走看看