【 shell 编程 】第4篇 数组和函数

news2024/9/23 9:33:34

数组和函数


文章目录

  • 数组和函数
  • 一、数组
    • 1.普通数组
    • 2.关联数组
    • 3.数组和循环
  • 二、函数
    • 1.定义函数
    • 2.调用函数


在这里插入图片描述


一、数组

变量:用一个固定的字符串,代替一个不固定字符串。
数组:用一个固定的字符串,代替多个不固定字符串。

1.普通数组

1、定义数组:

方法一: 一次赋一个值

数组名[ 下标 ]=变量值

[root@nfs ~]# array1[0]=apple
[root@nfs ~]# array1[1]=orange
[root@nfs ~]# array1[2]=pear
[root@nfs ~]# declare -a   
declare -a BASH_ARGC='()'
declare -a BASH_ARGV='()'
declare -a BASH_LINENO='()'
declare -a BASH_SOURCE='()'
declare -ar BASH_VERSINFO='([0]="4" [1]="2" [2]="46" [3]="2" [4]="release" [5]="x86_64-redhat-linux-gnu")'
declare -a DIRSTACK='()'
declare -a FUNCNAME='()'
declare -a GROUPS='()'
declare -a PIPESTATUS='([0]="0")'
declare -a array1='([0]="apple" [1]="orange" [2]="pear")'
[root@nfs ~]# declare -a | grep array1  //查看数组
declare -a array1='([0]="apple" [1]="orange" [2]="pear")'

[root@nfs ~]# echo $array1 //默认返回数组第一个值
apple
[root@nfs ~]# echo ${array1[1]}
orange
[root@nfs ~]# echo ${array1[2]}
pear

方法二: 一次赋多个值

[root@nfs ~]# array2=(luo guan tom)
[root@nfs ~]# echo ${array2[@]}
luo guan tom
[root@nfs ~]# echo ${!array2[@]}
0 1 2
[root@nfs ~]# declare -a | grep array2
declare -a array2='([0]="luo" [1]="guan" [2]="tom")'
[root@nfs ~]# array3=(`cat /etc/passwd`)
[root@nfs ~]# echo ${array3[0]}
root:x:0:0:root:/root:/bin/bash
[root@nfs ~]# array4=(`ls /home`)
[root@nfs ~]# echo ${array4[@]}
guan Guan guanguan Guanguan luo luo1 luo2 luo3 user0013 user3 userA userA1 userA2 userA3 userB userB1 userB2 userB3 userB4 userB5 userC userD
#" " 里面包含的字符串在数组中被看做一个元素
[root@nfs ~]# array5=(guan luo tom "hello word")
[root@nfs ~]# echo ${array5[0]}
guan
[root@nfs ~]# echo ${array5[1]}
luo
[root@nfs ~]# echo ${array5[2]}
tom
[root@nfs ~]# echo ${array5[3]}
hello word
[root@nfs ~]# echo ${array5[@]}
guan luo tom hello word元素可以是变量
#数组里的
[root@nfs ~]# student1=guan
[root@nfs ~]# student2=luo
[root@nfs ~]# students=($student1 $student2)
[root@nfs ~]# echo ${students[*]}
guan luo

2、访问数组元素:

#echo ${array[0]}:访问数组中的第一个元素
#echo ${array[@]}:访问数组中所有元素,等同于 echo ${array[*]}
#echo ${#array[@]}:统计数组元素的个数
#echo ${!array[@]}:获取数组元素的索引
#echo ${array[@]:1}:从数组下标1开始
#echo ${array[@]:1:2}:从数组下标1开始,访问两个元素

2.关联数组

注意:先声明关联数组
1、方法一:一次赋一个值
数组名[索引]=变量值

[root@nfs ~]# declare -A ass_array1
[root@nfs ~]# ass_array1[index1]=guan
[root@nfs ~]# ass_array1[index2]=luo
[root@nfs ~]# ass_array1[index3]=tom
[root@nfs ~]# echo ${ass_array1[*]}
guan luo tom

2、方法二:一次赋多个值

[root@nfs ~]# declare -A ass_array2
[root@nfs ~]# ass_array2=([index1]=tom [index2]=guan [index3]=luo [index4]="hello word")
[root@nfs ~]# echo ${ass_array2[*]}
hello word tom guan luo
[root@nfs ~]# echo ${!ass_array2[*]}
index4 index1 index2 index3

3.数组和循环

1、通过循环定义和显示数组

例子1:while 脚本快速定义数组

[root@nfs test]# vim test21.sh
[root@nfs test]# bash test21.sh
循环完成,输出数组
192.168.200.2 up 192.168.200.184 up 192.168.200.182 up
[root@nfs test]# vim test21.sh
[root@nfs test]# bash test21.sh
循环完成,输出数组
1: 192.168.200.2 up
2: 192.168.200.184 up
3: 192.168.200.182 up
[root@nfs test]# vim test21.sh
[root@nfs test]# cat test21.sh
#!/bin/bash
#循环读取文件,定义数组
while read line
do
#hosts:数组名
#[++i]:索引递增,++i是从1开始,i++是从0开始的
#$line:值,即文件中的内容
hosts[++i]=$line
done < /root/test/up.txt

echo "循环完成,输出数组"
for i in ${!hosts[*]}
do
echo "索引序号是:$i: 取值 ${hosts[$i]}"
done
[root@nfs test]# cat up.txt 
192.168.200.2 up
192.168.200.184 up
192.168.200.182 up


例子2:for脚本快速定义数组

[root@nfs test]# vim test22.sh
[root@nfs test]# bash test22.sh
0: 127.0.0.1
1: localhost
2: localhost.localdomain
3: localhost4
4: localhost4.localdomain4
5: ::1
6: localhost
7: localhost.localdomain
8: localhost6
9: localhost6.localdomain6
10: 192.168.200.182
11: nfs
12: 192.168.200.183
13: wbe3
14: 192.168.200.184
15: web1
16: 192.168.200.185
17: wbe2
18: 192.168.200.186
19: mycat
[root@nfs test]# cat test22.sh
#!/bin/bash
for line in `cat /etc/hosts`
do
hosts[i++]=$line
done

for i in ${!hosts[*]}
do
echo "$i: ${hosts[$i]}"
done
[root@nfs test]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.200.182 nfs
192.168.200.183 wbe3
192.168.200.184 web1
192.168.200.185 wbe2
192.168.200.186 mycat

[root@nfs test]# 
[root@nfs test]# vim test22.sh
[root@nfs test]# bash test22.sh
0: 127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
1: ::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
2: 192.168.200.182 nfs
3: 192.168.200.183 wbe3
4: 192.168.200.184 web1
5: 192.168.200.185 wbe2
6: 192.168.200.186 mycat
[root@nfs test]# cat test22.sh
#!/bin/bash
IFS=$'\n' //定义以换行符为分隔符
for line in `cat /etc/hosts`
do
hosts[i++]=$line
done

for i in ${!hosts[*]}
do
echo "$i: ${hosts[$i]}"
done
[root@nfs test]# 

2、通过数组统计数据

例子1:数组统计性别

[root@nfs test]# vim sex.txt
[root@nfs test]# vim sex.sh
[root@nfs test]# bash sex.sh
f:1
m:2
[root@nfs test]# cat sex.sh
#!/bin/bash
declare -A sex
while read line
do
	type=`echo $line | awk '{print $2}'`
	let sex[$type]++
done < sex.txt

for i in ${!sex[*]}
do
	echo "$i:${sex[$i]}"
done
[root@nfs test]# cat sex.txt
guan m
luo f
tom m

例子2:数组统计,用户shell 的类型和数量

[root@nfs test]# vim shell.sh
[root@nfs test]# bash shell.sh
/sbin/nologin:42
/bin/sync:1
/bin/bash:20
/sbin/shutdown:1
/sbin/halt:1
[root@nfs test]# cat shell.sh
#!/bin/bash
declare -A shells
while read ll 
do
type=`echo $ll | awk -F: '{print $NF}'`
let shells[$type]++
done < /etc/passwd

for i  in ${!shells[*]}
do
echo "$i:${shells[$i]}"
done

二、函数

1.定义函数

方法一:

函数名(){
函数要实现的功能代码
}

方法二:

function 函数名 {
函数要实现的功能代码
}

例子1
编写脚本,实现如下菜单的功能

provide these tools:
show disk info(d)
show mem info(m)
show cpu  info(c)
quit(q)
[root@nfs test]# vim tool.sh
[root@nfs test]# bash tool.sh
provide these tools:
show disk info(d)
show mem info(m)
show cpu  info(c)
quit(q)
:d
-------------disk info------------------
文件系统                类型      容量  已用  可用 已用% 挂载点
/dev/mapper/centos-root xfs        17G  8.4G  8.7G   50% /
devtmpfs                devtmpfs  894M     0  894M    0% /dev
tmpfs                   tmpfs     910M     0  910M    0% /dev/shm
tmpfs                   tmpfs     910M   22M  889M    3% /run
tmpfs                   tmpfs     910M     0  910M    0% /sys/fs/cgroup
/dev/sda1               xfs      1014M  179M  836M   18% /boot
tmpfs                   tmpfs     182M  4.0K  182M    1% /run/user/42
tmpfs                   tmpfs     182M  4.0K  182M    1% /run/user/0
provide these tools:
show disk info(d)
show mem info(m)
show cpu  info(c)
quit(q)
:m
---------------mem info------------------
              total        used        free      shared  buff/cache   available
Mem:           1819         452          73          21        1294        1124
Swap:          2047           0        2047
provide these tools:
show disk info(d)
show mem info(m)
show cpu  info(c)
quit(q)
:c
-----------------cpu info------------------
 19:23:03 up  8:09,  2 users,  load average: 1.02, 1.09, 1.13
provide these tools:
show disk info(d)
show mem info(m)
show cpu  info(c)
quit(q)
:q
----------------- exit ---------------------
[root@nfs test]# cat tool.sh
#!/bin/bash
menu () {
cat << EOF
provide these tools:
show disk info(d)
show mem info(m)
show cpu  info(c)
quit(q)
EOF

}

#cat << EOF
#provide these tools:
#show disk info(d)
#show mem info(m)
#show cpu  info(c)
#quit(q)
#EOF

menu

while :
do
 

read -p ":" choice
case $choice in
d)
echo "-------------disk info------------------"
df -hT
;;
m)
echo "---------------mem info------------------"
free -m
;;
c)
echo "-----------------cpu info------------------"
uptime
;;
q)
echo "----------------- exit ---------------------"
exit
;;
*)
#cat << EOF
#provide these tools:
#show disk info(d)
#show mem info(m)
#show cpu  info(c)
#quit(q)
#EOF
menu

esac
done
[root@nfs test]# 

2.调用函数

语法:

函数名
函数名 参数1 参数2

例子2
数的阶乘

[root@nfs test]# vim fac.sh
[root@nfs test]# bash fac.sh
请输入你想阶乘结果的数:9
9阶乘的结果为:362880
[root@nfs test]# cat fac.sh
#!/bin/bash
#定义函数名fun
read -p "请输入你想阶乘结果的数:" num
fun () {
#初值为1
fac=1
#使用阶乘循环
for((i=1;i<=$num;i++))
do
#阶乘公式
fac=$[$fac*$i]
done
echo "$num阶乘的结果为:$fac"
}
fun

[root@nfs test]# vim fac.sh
[root@nfs test]# bash fac.sh
6阶乘的结果为:720
7阶乘的结果为:5040
8阶乘的结果为:40320
[root@nfs test]# cat fac.sh
#!/bin/bash
#定义函数名fun

fun () {
#初值为1
fac=1
#使用阶乘循环
for((i=1;i<=$1;i++))
do
#阶乘公式
fac=$[$fac*$i]
done
echo "$1阶乘的结果为:$fac"
}
fun  $1  //传参
fun  $2   
fun  $3
[root@nfs test]# bash fac.sh 10 11 12
10阶乘的结果为:3628800
11阶乘的结果为:39916800
12阶乘的结果为:479001600


[root@nfs test]# vim test23.sh
[root@nfs test]# bash test23.sh
输出加工后的数组
6 7 8
[root@nfs test]# cat test23.sh
#!/bin/bash
num=(1 2 3)
array () {
for i in $*
do
outarray[j++]=$[$i+5]

done
echo "输出加工后的数组"
echo ${outarray[*]}
}

result=`array ${num[*]}`
echo ${result[*]}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/133404.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Python代码实现学生管理系统

Python代码实现学生管理系统 需求说明 实现一个命令行版本的学生管理系统 功能: 新增学生 显示学生 查找学生 删除学生 存档到文件 创建入口函数 使用一个全局列表 students 表示所有学生信息. 使用 menu 函数和用户交互. 这是一个自定义函数. 使用 insert , show ,…

MacOS Ventura安装失败的原因及解决方法分享

2022年10月&#xff0c;苹果公司向Mac电脑用户推送了MacOS Ventura正式版更新&#xff0c;此次更新为MacOS带来了台前调度、连续互通相机、iMessage 撤回、编辑等功能。吸引众多Mac电脑用户不由纷纷下载安装&#xff0c;但各用户在安装的过程中经常遇到更新MacOS Ventura时突然…

物联网与射频识别技术,课程实验(五)

实验5—— 基于随机二进制树的防冲突算法的实现与性能分析 实验说明&#xff1a; 利用Python或Matlab模拟基于随机二进制树的防冲突算法&#xff1b; 分析标签数量k对遍历所有标签所需时间的影响&#xff1b; 分析标签ID的长度、分布对算法性能的影响&#xff1b; 利用Python或…

MQTT+STM32+ESP8266-01s硬件传递的JSON数据到前端和后端出现中文乱码问题

最近在做一个关于MQTT相关毕设项目,数据传输过程中出现了中文乱码问题,大致就是硬件发送的JSON主题数据中包含中文(如下图1所示),软件后端和软件前端接受该主题数据后出现了中文乱码,出现乱码一般都是硬件传递到后端和前端的编码不一致导致的,所以前端和后端接受该JSON数据的时…

2023.1.1 学习周报

文章目录摘要文献阅读1.题目2.摘要3.问题和方案4.介绍5.方法5.1 Symbolic Description5.2 The Short-Term Memory Priority Model5.3 The STAMP Model5.4 The Short-Term Memory Only Model6.实验6.1 评价指标6.2 实验结果7.结论深度学习加性模型点积模型缩放点积模型双线性模型…

数值优化之凸函数

本文ppt来自深蓝学院《机器人中的数值优化》 目录 1 凸函数的性质 ​2 凸函数的性质 1 凸函数的性质 凸函数最重要的性质就是Jensens inequality,也就是琴生不等式。 若能取到等号则是凸函数&#xff0c;若不能取到等号则是强凸函数&#xff0c;若不等号相反&#xff0c;则…

spring session

文章目录Spring Session 架构及应用场景为什么要spring-sessionSR340规范与spring-session的透明继承Spring Session探索特点核心 APIservlet session 与 spring-session 关系webflux 与 spring session 的关系基于 Servlet 的 Spring Session 实现思考题背景1、注册到 Filter …

Java 并发编程知识总结【一】

JUC 是什么&#xff1f; java.util.concurrent 在并发编程中使用的工具类 concurrent:并发 1. 线程基础知识复习 1.1 进程(process) 进程是程序的一次执行过程&#xff0c;或是正在运行的一个程序。是一个动态的过程&#xff1a;有它自身的产生、存在和消亡的过程(生命周期…

【数据集7】全球人类住区层GHSL数据详解

全球人类住区层Global Human Settlement Layer 官网地址-GHSL - Global Human Settlement Layer 1 全球人类住区层GHS-SMOD Global human settlement layer-settlement model grid (GHS-SMOD)&#xff1a;描述 epoch时段: 1975-2030年 5年一个周期resolution空间分辨率: …

Codeforces Round #833 (Div. 2)E. Yet Another Array Counting Problem(笛卡尔树+树形DP)

题目链接&#xff1a;Problem - E - Codeforces 样例输入&#xff1a; 4 3 3 1 3 2 4 2 2 2 2 2 6 9 6 9 6 9 6 9 9 100 10 40 20 20 100 60 80 60 60样例输出&#xff1a; 8 5 11880 351025663题意&#xff1a;给定一个长度为n的数组a[],对于每一个区间[l,r]&#xff0c;这个…

[Python从零到壹] 六十一.图像识别及经典案例篇之基于纹理背景和聚类算法的图像分割

祝大家新年快乐&#xff0c;阖家幸福&#xff0c;健康快乐&#xff01; 欢迎大家来到“Python从零到壹”&#xff0c;在这里我将分享约200篇Python系列文章&#xff0c;带大家一起去学习和玩耍&#xff0c;看看Python这个有趣的世界。所有文章都将结合案例、代码和作者的经验讲…

尚医通-查询删除科室接口-添加查询删除排班接口实现(二十)

目录&#xff1a; &#xff08;1&#xff09;数据接口-查询和删除科室接口-功能实现 &#xff08;2&#xff09;数据接口-排版接口-功能实现 &#xff08;1&#xff09;数据接口-查询和删除科室接口-功能实现 查看医院系统中查询科室的对应的方法 查询条件需要用的类&#…

【数据结构】链式存储:链表

目录 &#x1f947;一&#xff1a;初识链表 &#x1f392;二、链表的实现&#xff08;单向不带头非循环&#xff09; &#x1f4d8;1.创建节点类 &#x1f4d2;2.创建链表 &#x1f4d7;3.打印链表 &#x1f4d5;4.查找是否包含关键字key是否在单链表当中 &#x1f4d9;…

Webpack核心概念

1. 核⼼概念 Entry Entry ⽤来指定 webpack 的打包⼊⼝。 依赖图的⼊⼝是 entry&#xff0c;对于⾮代码⽐如图⽚、字体依赖也会不断加⼊到依赖图中。 Entry 的⽤法&#xff1a; 1. 单⼊⼝&#xff1a;entry 是⼀个字符串&#xff1b; module.exports {entry: ./path/to/my…

若依框架-补充篇:Vuex全局状态管理Axios二次封装

在上一篇《若依框架&#xff1a;前端登录组件与图像验证码|用户登录逻辑》中的篇末&#xff0c;对Vuex全局状态管理、Axios二次封装部分介绍的较为粗略&#xff0c;因此就有了这个补充篇。 目录 Vuex全局状态管理 Vuex是什么&#xff1f; 如何理解“状态管理模式”&#xf…

【Java语法】之String类练习1

目录 1.字符串中的第一个唯一字符 2. 最后一个单词的长度 58. 最后一个单词的长度 3.验证回文串 4.字符串相加 5.小结&#xff1a; 1.字符串中的第一个唯一字符387. 字符串中的第一个唯一字符https://leetcode.cn/problems/first-unique-character-in-a-string/ 给定一个字符…

【免费开放源码】审批类小程序项目实战(活动申请详解)

第一节&#xff1a;什么构成了微信小程序、创建一个自己的小程序 第二节&#xff1a;微信开发者工具使用教程 第三节&#xff1a;深入了解并掌握小程序核心组件 第四节&#xff1a;初始化云函数和数据库 第五节&#xff1a;云数据库的增删改查 第六节&#xff1a;项目大纲以及制…

Mac下安装go

1.下载地址 ​​​​​​https://golang.google.cn/dl/ 2.安装Go 3.查看安装效果 go version go env 4.安装vscode和插件 4.1.安装vscode https://code.visualstudio.com/Download 4.2.安装GO插件 4.3.设置goproxy 执行命令&#xff1a;vim ~/.bash_profile export GO1…

数值分布的分散程度对迭代次数的影响

( A, B )---1*30*2---( 1, 0 )( 0, 1 ) 让网络的输入只有1个节点&#xff0c;AB各由7张二值化的图片组成&#xff0c;排列组合A和B的所有可能性&#xff0c;固定收敛误差为7e-4&#xff0c;统计收敛迭代次数 1 2 3 4 5 6 7 迭代次数 1b 1b 1b 1b 1b 1b 0 0*0*0…

PHP---文件上传

目录 一、文件上传的概念 二、文件上传的步骤 &#xff08;1&#xff09;表单的制作 三、$_FILES详解 &#xff08;1&#xff09;name &#xff08;2&#xff09;tmp_name &#xff08;3&#xff09;type &#xff08;4&#xff09;error &#xff08;5&#xff09;si…