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 
相关推荐
2401_8784545331 分钟前
HTML和CSS的复习2
前端·css·html
We་ct39 分钟前
吃透现代CSS全技术体系
前端·css·css3·sass·postcss·预处理器
ZC跨境爬虫39 分钟前
跟着 MDN 学 HTML day_11:(语义化容器全站重构+独立CSS拆分+字体合规引入)
前端·css·ui·重构·html·edge浏览器
ZC跨境爬虫42 分钟前
跟着 MDN 学 HTML day_10:(超链接核心语法+路径规则)
前端·css·笔记·ui·html·edge浏览器
GISer_Jing1 小时前
AI原生前端工程化进阶实践:从流式交互架构到端云协同全链路落地
前端·人工智能·后端·学习
被考核重击1 小时前
Vue响应式原理(下)
前端·javascript·vue.js
ZC跨境爬虫9 小时前
跟着 MDN 学 HTML day_9:(信件语义标记)
前端·css·笔记·ui·html
前端老石人10 小时前
HTML 字符引用完全指南
开发语言·前端·html
幼儿园技术家10 小时前
前端如何设计权限系统(RBAC / ABAC)?
前端
前端摸鱼匠12 小时前
Vue 3 的v-bind合并行为:讲解v-bind与普通属性合并的规则
前端·javascript·vue.js·前端框架·ecmascript