Shell脚本(四)

一、函数

1、函数的定义

方式一:

function name {

commands

}

name:为函数的唯一函数名,不要与特殊含义的命令名重复

commands:构成函数的bash shell命令,依次执行

方式二:

name() {

commands

}

二、调用函数

函数的调用只需要指定函数名即可。每次执行函数时bash shell会找到函数的定义执行,函数的定义必须在使用前,否则会报错

1、返回值

通常情况下,函数的退出状态码为函数的最后一条命令返回的退出状态码,函数结束后可用$?查看,状态码为1,表示最后一条命令失败,为0表示成功

2、return

return:用于返回退出状态码

3、函数中的变量

全局变量:全局有效,可能会受到影响.

局部变量 :在变量声明前加上local关键字,仅在函数内部有效

4、传参

传递数组参数:不能直接将数组作为参数,否则仅传递数组中的第一个参数,需将数组拆分传递使用(echo {myarray\*})

返回数组:使用echo依次输出单个值,后重新放入一个新的数组

复制代码
#!/bin/bash 
# returning an array value 
function arraydblr { 
   local origarray 
   local newarray 
   local elements 
   local i 
   origarray=($(echo "$@")) 
   newarray=($(echo "$@")) 
   elements=$[ $# - 1 ] 
   for (( i = 0; i <= $elements; i++ )) 
   { 
      newarray[$i]=$[ ${origarray[$i]} * 2 ] 
   } 
   echo ${newarray[*]} 
} 
myarray=(1 2 3 4 5) 
echo "The original array is: ${myarray[*]}" 
arg1=$(echo ${myarray[*]}) 
result=($(arraydblr $arg1)) 
echo "The new array is: ${result[*]}" 
$  
$ ./test12 
The original array is: 1 2 3 4 5 
The new array is: 2 4 6 8 10 

三、函数库

由于bash是在一个子进程中运行,使用函数库需要使用source命令连接上下文,

创建一个myfuncs的函数库,使用路径调用

复制代码
#!/bin/bash 
# using functions defined in a library file 
. ./myfuncs 
value1=10 
value2=5 
result1=$(addem $value1 $value2) 
result2=$(multem $value1 $value2) 
result3=$(divem $value1 $value2) 
echo "The result of adding them is: $result1" 
echo "The result of multiplying them is: $result2" 
echo "The result of dividing them is: $result3" 
$  
$ ./test14 
The result of adding them is: 15 
The result of multiplying them is: 50 
The result of dividing them is: 2 
相关推荐
计算机魔术师2 分钟前
科技巨头砸7400亿押注AI,为什么苹果成了唯一赢家?
前端
QianhangQianping11 分钟前
撤销重做不是「存快照」:一个可视化编辑器的Operation 设计
java·前端·数据库·typescript·编辑器·前端架构·撤销重做
Nymph_Zhu1 小时前
pdf转换markdown预览及内容互相点击定位
前端·pdf·vue3·markdown·element-plus
计算机魔术师1 小时前
Google 一天蒸发5000亿,Reddit 靠 AI 训练喂得饱自己却饿死
前端
小大宇1 小时前
Vue知识点-ElementPlus-05 输入框
前端·javascript·vue.js
l1m0_2 小时前
AI设计工具有哪些?Paico、Pixso AI、墨刀AI、Lovable、Codex怎么选
前端·人工智能·ai·设计·墨刀·codex·pixso
web打印社区2 小时前
Lodop在Edge和双核浏览器-先分清内核
前端·javascript·edge·pdf·ecmascript·html5
西瓜拿铁好喝2 小时前
开源和闭源 AI 办公工具,分别适合谁
java·前端·数据库
IT_陈寒2 小时前
深入理解SpringBoot:核心原理与最佳实践
前端·人工智能·后端
风骏时光牛马2 小时前
大模型综合能力多维评测:性能、逻辑与落地表现对比
前端