Shell 脚本成长笔记程序员@IT·互联网

Shell 函数(二) 函数的参数、变量与返回值

2017-04-15  本文已影响65人  赵者也

函数的参数

Shell 函数有自己的命令行参数。函数使用特殊变量 $1,$2,$3,...,$N 来访问传递给它的参数。函数中使用参数的语法规则如下:

name() {
    arg1=$1
    arg2=$2
    command on $arg1
}

我们可以使用如下语法来调用函数:

name LiLei HanMeimei

下面是一个简单的实例脚本:

#! /bin/bash

test(){
    a=$1
    # 打印脚本的名称
    echo "test(): \$0 is $0"
    
    echo "test(): \$1 is $1"
    echo "test(): \$a is $a"
    
    # 传递给函数的参数的个数
    echo "test(): total args $#"
    
    # 打印传递给函数的所有参数
    echo "test(): total args (\$@) - \"$@\""
    # 打印传递给函数的所有参数
    echo "test(): total args (\$*) - \"$*\""
}

echo "******** call test() *******"
test first

echo "******** call test() once *******"
test first second third

上述脚本的运行结果:

输出结果

本地变量

默认情况下脚本中所有的变量都是全局的,在函数中修改一个变量将改变这个脚本中此变量的值,这在某些情况下可能是个问题,例如,如下脚本:

#! /bin/bash
function create_logFile() {
    d=$1
    echo "create_logFile(): d is set to $d"
}

d=/tmp/diskUsage.log
echo "Before calling create_logFile d is set to $d"

create_logFile "/home/toby/diskUsage.log"
echo "After calling create_logFile d is set to $d"

此脚本的运行结果如下:


2017041501

根据上述情况,我们可以使用 local 命令来创建一个本地变量,其语法如下所示:

local var=value
local varName

或者

function name() {
    local var=$1
    command on $var
}

注意:

  1. local 命令只能在函数内部使用;
  2. local 命令将变量名的可见范围限制在函数内部。
#! /bin/bash

function create_logFile() {
    local d=$1
    echo "create_logFile(): d is set to $d"
}

d=/tmp/diskUsage.log
echo "Before calling create_logFile d is set to $d"

create_logFile "/home/toby/diskUsage.log"
echo "After calling create_logFile d is set to $d"

下面是调整之后的脚本的运行结果:

2017041502

return 命令

如果在函数里有 Shell 内置命令 return,则函数执行到 return 语句时结束,并返回到 Shell 脚本中调用函数位置的下一个命令。如果 return 带有一个数值型参数,则这个参数就是函数的返回值(0 ~ 255);否则,函数的返回值是函数体内最后一个执行的命令的返回状态。
下面是一个函数中使用 return 命令的例子:

# 检查某个进程号是否运行

function checkPid() {
    local i
    for i in $*
    do
        # 如果进程在运行,则在 /proc 目录下会存在一个以进程号命名的子目录
        [-d "/proc/$i"] && return 0
    done
    
    return 1
}

下面是包含函数返回值得测试的完整的脚本:

#! /bin/bash

# 检查某个进程号是否运行

function checkPid() {
    local i
    for i in $*
    do
        # 如果进程在运行,则在 /proc 目录下会存在一个以进程号命名的子目录
        [ -d "/proc/$i" ] && return 0
    done

    return 1
}

# test 01
checkPid 1002 2003 3004

if [ $? = 0 ]
then
    echo "The one of them is running."
else
    echo "Thess PIDs are not running."
fi

# test 02

if ( checkPid 1002 2568 3004 )
then
    echo "The one of them is running."
else
    echo "Thess PIDs are not running."
fi

echo "Ending"

在运行上述脚本之前先看下系统正在运行的进程,以便进行测试:

2017041503

脚本的实际运行结果:

2017041504

本文参考自 《Linux Shell命令行及脚本编程实例详解

上一篇 下一篇

猜你喜欢

热点阅读