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 
相关推荐
kyriewen9 小时前
Anthropic 估值逼近万亿美元,Claude Sonnet 5 + Claude Science 一天两连发
前端·ai编程·claude
小徐_233310 小时前
Wot UI 2.2.0 发布:Button 新增 subtle,VideoPreview 预览体验继续增强
前端·微信小程序·uni-app
天蓝色的鱼鱼12 小时前
关于 CSS 你可能不知道的属性,但关键时刻很有用
前端·css
泯泷13 小时前
第 2 篇:设计第一套字节码:Opcode、Instruction 与 Constant Pool
前端·javascript·安全
妙码生花13 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十五):优化细节、网络请求封装
前端·后端·ai编程
泯泷13 小时前
第 1 篇:从 1 + 2 开始:亲手写出第一台 JSVM
前端·javascript·安全
团团崽_七分甜13 小时前
Spring Boot 核心知识点总结
前端
lichenyang45314 小时前
从一个按钮开始,理解 ASCF 框架到底在做什么
前端
古夕14 小时前
第三方 SSO 接入实践:redirect_uri 编码、回调一致性与跨项目联调
前端·vue.js