linux shell中创建函数
001、
[root@pc1 test]# cat test.sh ## 函数脚本 #!/bin/bash function db1 ## function关键字来定义函数,db1是函数名 { read -p "请输入:" value return $[$value *2] ## return返回函数值 } db1 ## 函数调用 echo $?
[root@pc1 test]# bash test.sh ## 在脚本中运行函数 请输入:45 90
002、
[root@pc1 test]# ls test.sh [root@pc1 test]# cat test.sh ## 修改上面的函数脚本 #!/bin/bash function db1 { read -p "请输入:" value echo $[$value *2] ## 将return改为了echo } db1 ## echo $? ## 函数返回值可以省略该句
调用测试:
[root@pc1 test]# ls test.sh [root@pc1 test]# cat test.sh ## 函数脚本 #!/bin/bash function db1 { read -p "请输入:" value echo $[$value *2] } db1 ## echo $? [root@pc1 test]# bash test.sh ## 执行脚本 请输入:45 90
003、
[root@pc1 test]# ls test.sh [root@pc1 test]# cat test.sh ## 函数脚本 #!/bin/bash function db1() ## 定义函数名时,在函数名后面增加小括号,不影响函数的调用 { read -p "请输入:" value echo $[$value *2] } db1
[root@pc1 test]# ls test.sh [root@pc1 test]# cat test.sh ## 脚本 #!/bin/bash function db1() { read -p "请输入:" value echo $[$value *2] } db1 [root@pc1 test]# bash test.sh ## 执行 请输入:47 94
004、小括号的作用
01、有关键字function的情况下,函数名后面可以又括号,也可以无括号
02、无关键字funtion的情况下, 函数名后面必须有括号
a、有fuancion情况
[root@pc1 test]# ls │[root@pc1 test]# ls 001.sh 002.sh │001.sh 002.sh [root@pc1 test]# cat 001.sh │[root@pc1 test]# cat 002.sh #/bin/bash │#/bin/bash │ function db1() │function db1 { │{ value=10 │ value=10 echo $[$value *2] │ echo $[$value *2] } │} │ db1 │db1 [root@pc1 test]# │[root@pc1 test]#
两者多函数的使用没有影响:
b、无function的情况
002.sh相对于001.sh,函数名后边少了小括号, 其余都一样:
执行效果:
以上说明在又function的情况下, 函数名后面有无括号对函数的使用没有影响;
在无function的情况下,函数名后面无小括号将无法正常调用。
005、函数的传参
[root@pc1 test]# ls 001.sh [root@pc1 test]# cat 001.sh ## 测试函数 #/bin/bash function db1() { value=$(($1 + $2)) ## $1 和 $2分别代表位置参数1和位置参数2 echo $[$value *2] } db1 $1 $2 ## 调用函数时,需要标明位置参数 [root@pc1 test]# bash 001.sh 3 4 ## 执行脚本,给与位置参数1值和位置参数2值 14
。
参考:
01、https://blog.csdn.net/datangda/article/details/130556349
分类:
linux shell
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2022-10-14 configure: error: htscodecs submodule files not present.
2022-10-14 centos中 在线安装 libz
2022-10-14 slurm、docker
2022-10-14 centos7 中 升级cmake
2022-10-14 linux 中如何统计每一行所占的字符长度
2022-10-14 centos7 中manta软件的安装
2020-10-14 linux系统中case命令的用法