第三章、shell语法 函数 和 exit 命令

2022/7/10 5:20:02

本文主要是介绍第三章、shell语法 函数 和 exit 命令,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

第三章、shell语法 函数 和 exit 命令

函数

shell中的函数和 c/c++中的函数类似,但是在函数输出和返回值方面有些许的不同。
函数return返回值: 函数返回的是 exit code,可以通过 $? 变量获取。
函数输出: 函数中 echo的字符查,在stdout中,可以通过$(function_name 参数)获取

函数返回值exit code和输出output

函数定义

[function] function_name() {    # function关键字可以省略
    sentence1
    sentence2
    return exit_code     # 不指定 exit_code 时候,默认为 0,可以直接写 return,或者是连 return 也不写
}

函数不获取 exit code 和 output

#! /bin/bash

function test1() {
    if [ $1 -eq 0 ] 
    then
        echo "\$1 == 0"
        return 0    
    else
        echo "\$1 != 0"
        return 155 
    fi  
}

test1 2
echo $?

输出

$1 != 0
155

函数获取 exit code 和 output

#! /bin/bash

function test1() {
    if [ $1 -eq 0 ]
    then
        echo "\$1 == 0"
        return 0
    else
        echo "\$1 != 0"
        return 155
    fi
}

output=$(test1 2)
exit_code=$?


echo "output=${output}"
echo "exit_code=${exit_code}"

输出

output=$1 != 0
exit_code=155

函数参数

函数参数的传递
函数中 $0表示文件名,注意是文件名,不是函数名
$1$2这些仍是位置参数。
我们在上面的例子中,已经有过使用。

现在让我们递归计算 0 + 1 + 2 + ... + $1
首先想,需要使用 echo,因为返回值只能是 0-255

function dfs() {
    if [ $1 -eq 0 ]
    then
        echo 0
        return 0
    else
        pre_output=$(dfs `expr $1 - 1`)
        echo "`expr ${pre_output} + $1`"
        return 0
    fi
}

res=$(dfs 10)
echo $res

输出

55

函数局部变量

#! /bin/bash


function func() {
    local name='xyg'
    echo "inside ${name}"
    return 0
}


func

echo "outside ${name}"

输出

inside xyg
outside

倘若不定义局部变量

#! /bin/bash


function func() {
    name='xyg'
    echo "inside ${name}"
    return 0
}


func

echo "outside ${name}"

输出:

inside xyg
outside xyg

注意和 export 区分,export全局变量是 子进程也可以使用!

exit 命令

之前函数,关键字return是用于退出函数,并指定exit_code默认为0。
在脚本bash中存在关键字exit exit_code,来退出当前shell进程,并返回一个退出状态;同样是使用$?可以接收这个退出状态。
可以接受一个整数值(0-255)作为参数,代表退出状态。如果不指定,默认状态值是 0。所有的返回状态中,只有0表示正常退出。

脚本事例

#! /bin/bash

if [ $# -eq 3 ]    # 位置参数数量 = 3,才是合法
then
    echo "legal arguments"
    exit 0
else
    echo "illegal arguments"
    exit 1
fi

输出

(base) xyg@vivo-xyg:~/xyg/test$ ./test.sh    # 没有参数,illegal 
illegal arguments
(base) xyg@vivo-xyg:~/xyg/test$ echo $?
1
(base) xyg@vivo-xyg:~/xyg/test$ ./test.sh 1 2    # 两个参数 illegal
illegal arguments
(base) xyg@vivo-xyg:~/xyg/test$ echo $?
1
(base) xyg@vivo-xyg:~/xyg/test$ ./test.sh 1 2 3    # 三个参数 legal
legal arguments
(base) xyg@vivo-xyg:~/xyg/test$ echo $?
0

参考文献

强烈推荐 Y总的基础课
linux教程-孟庆昌



这篇关于第三章、shell语法 函数 和 exit 命令的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程