linux shell 命令 line-07-func 函数
最编程
2024-03-14 16:18:17
...
拓展阅读
linux Shell 命令行-00-intro 入门介绍
linux Shell 命令行-02-var 变量
linux Shell 命令行-03-array 数组
linux Shell 命令行-04-operator 操作符
linux Shell 命令行-05-test 验证是否符合条件
linux Shell 命令行-06-flow control 流程控制
linux Shell 命令行-07-func 函数
linux Shell 命令行-08-file include 文件包含
linux Shell 命令行-09-redirect 重定向
函数
[ function ] 函数名 [()]
{
动作;
[返回值;]
}
示例
#!/bin/sh
# 函数演示
firstFunc() {
echo "这是我的第一个 Shell 函数。"
}
echo "函数开始"
firstFunc
echo "函数结束"
运行
houbinbindeMacBook-Pro:shell houbinbin$ vi function.sh
houbinbindeMacBook-Pro:shell houbinbin$ chmod +x function.sh
houbinbindeMacBook-Pro:shell houbinbin$ ./function.sh
函数开始
这是我的第一个 Shell 函数。
函数结束
带返回值的函数
#!/bin/sh
# 带返回值的函数
funcWithReturnVal() {
echo "输入第一个数字: "
read firstNum
echo "输入第二个数字: "
read secondNum
return $(($firstNum+$secondNum))
}
echo "带返回值的函数开始:"
funcWithReturnVal
returnVal=$?
echo "结果: $returnVal"
运行
houbinbindeMacBook-Pro:shell houbinbin$ ./funcWithReturnVal.sh
带返回值的函数开始:
输入第一个数字:
1
输入第二个数字:
2
结果: 3
带参数的函数
#!/bin/sh
# 带参数的函数
hasParam() {
echo "所有参数为 $*"
if [ $# -gt 0 ]
then
echo "有参数"
return 1
else
echo "没有参数"
return 0
fi
}
hasParam 1 2 3
运行
houbinbindeMacBook-Pro:shell houbinbin$ vi funcWithParam.sh
houbinbindeMacBook-Pro:shell houbinbin$ chmod +x funcWithParam.sh
houbinbindeMacBook-Pro:shell houbinbin$ ./funcWithParam.sh
所有参数为 1 2 3
有参数
使用$n
获取参数值,当 n >= 10 时,使用 ${n}
!
本文由博客一文多发平台 OpenWrite 发布!
上一篇: 计算机网络 - 数据包延迟、损耗和吞吐量
推荐阅读
-
Linux C 程序调用外部程序的几种方法 - 系统(执行 shell 命令)
-
linux class设置]自实现的 shell 命令行解释器
-
linux shell 使用 sed 命令在一行文本的末尾或开头添加字符。
-
linux shell 命令 line-07-func 函数
-
linux efi shell,EFI Shell 命令描述 "建议收藏"。
-
二十七.Linux 下常用 shell 命令记录
-
深入理解Linux与macOS平台的Shell环境:tar与zip命令操作指南
-
简易上手:在Linux Shell中,执行多个命令的不同技巧 - 1. 用分号 (;) 连接各命令
-
实战!Linux Shell编程学习笔记第42篇:探索hdparm命令的奥秘
-
实战Linux服务器必备!一起学习和掌握Shell命令(下篇:问题排查)