Shell 脚本编程:函数

Shell 脚本编程:函数

将命令序列按格式写在一起

可重复使用命令序列

一、函数定义格式

格式一:
shell 复制代码
function 函数名 {
    命令序列
}
格式二:
shell 复制代码
函数名() {
    命令序列
}

二、函数返回值

  • 使用 return 返回值(0-255),可通过 $? 获取

  • 0-255,超出时 除以256取余

示例:
shell 复制代码
#!/bin/bash
function cy {
        read -p "请输入一个整数: " n
        return $[n*2]
}
cy
echo "返回值: $?"

3. 函数传参与变量作用域

函数变量的作用范围(局部变量以及全局变量)

函数在shell脚本中仅在当前shell环境中有效

shell脚本中变量默认全局有效

将变量限定一个函数的内部local,即局部变量

示例:传参计算两数之和
shell 复制代码
#!/bin/bash
sum() {
        sum=$[ $1 + $2 ]
        echo $sum
}
sum $1 $2
示例:局部变量与全局变量

将变量限定在函数内部使用local命令

即这个local的变量仅仅在当前的函数内有效,在别的函数中无效

shell 复制代码
#!/bin/bash
abc() {
        echo "函数内未定义local的i: $i"
        let i++
        local i
        i=6
        echo "函数内local的i: $i"
}
i=9
abc
echo "函数外的i: $i"

四、递归函数

示例:计算阶乘
shell 复制代码
#!/bin/bash
function yy() {
        if [ $1 -eq 1 ]; then
                echo 1
        else
                local temp=$[$1 - 1]
                local result=$(yy $temp)
                echo $[result * $1]
        fi      
}
read -p "输入一个值: " value
result=$(yy $value)
echo "阶乘值为: $result"

五、函数库

将常用函数集中在一个脚本中,方便其他脚本调用

示例

编辑函数库脚本

shell 复制代码
#!/bin/bash
jia() {
        result=$[$1 + $2]
        echo "$result"
}

jian() {
        result=$[$1 - $2]
        echo "$result"
}

cheng() {
        result=$[$1 * $2]
        echo "$result"
}

chu() {
        if [ $2 -ne 0 ]; then
                result=$[$1 / $2]
                echo "$result"
        else
                echo "除法中分母不能为0"
        fi
}

编辑调用函数库脚本

shell 复制代码
#!/bin/bash
. /root/test5.sh

read -p "请输入第一个数字: " n
read -p "请输入第二个数字: " m

result1=$(jia $n $m)
result2=$(jian $n $m)
result3=$(cheng $n $m)
result4=$(chu $n $m)

echo "两数之和为: $result1"
echo "两数之差为: $result2"
echo "两数之积为: $result3"
echo "两数之商为: $result4"
相关推荐
weixin_5160230718 分钟前
linux下fcitx5拼音的安装
linux·运维·服务器
hunter14501 小时前
Linux 进程与计划任务
linux·运维·服务器
shizhenshide1 小时前
社交媒体自动化:批量注册/发帖的验证码难题一站式解决
自动化·php·媒体·验证码·ezcaptcha
楼田莉子1 小时前
Linux学习之磁盘与Ext系列文件
linux·运维·服务器·c语言·学习
陌上花开缓缓归以1 小时前
linux 怎么模拟系统panic重启
linux·运维·服务器
KL's pig/猪头/爱心/猪头2 小时前
写一个rv1106的led驱动3-功能函数编写
linux·驱动开发·rv1106
月白风清江有声2 小时前
vscode使用git
linux·运维·服务器
zl_dfq2 小时前
Linux 之 【文件】(ext2文件系统、目录、软硬链接)
linux
物理与数学2 小时前
Linux 内核 LRU 页面置换算法
linux·linux内核
小白同学_C4 小时前
Lab1-Xv6 and Unix utilities 配置环境的搭建以及前言 && MIT6.1810操作系统工程【持续更新】
linux·c/c++·操作系统os