函数与数组

函数与数组

1.函数概述

1.什么是Shell函数
函数其实就是一堆命令的合集 ,用来完成特定功能的代码块。
2.为什么要使用函数
比如:我们经常需要使用判断功能,完全可以将其封装为一个函数 ,这样在写程序过程中可以在
任何地方调用该函数,不必重复编写。这样能减少代码冗余,可读性更强。
函数和变量类似,必须先定义才可以调用,如果定义不调用则不会被执行。

2.函数基础语法

1.定义Shell函数,可以通过如下两种方式进行定义。

#第一种
fun() {
echo "123"
}
#第二种方式
function fun_Status{
echo "456"
	}
fun
fun_Status

###执行结果
123
456

3.函数参数传递

在函数内部可以使用参数$1、$2.. ,调用函数function_ name $1 $2..
1.函数中传递参数
[root@bgx she11]# fun2() { echo "hello, $1"; }
#调用
[root@bgx she1l]# fun2 Linux
hello, Linux

1.如何定义函数和调用函数
fun01 () { echo "Hello World"; }
fun01
2.如何给函数传递一-个参数
fun01 () { echo "Hello $1"; }
fun01 Shell
#执行时跟上一个固定的参数
fun01 $1
#执行时跟上一个不固定的参数
(脚本的位置参数,需要执行脚本时传递)
3.函数接收N多个参数传递
fun01 () { echo "Hello $*"; }
fun01 liunx shell Python

4.函数的返回值

#1. shell函数echo返回字符串结果示例一
[root@bgx shel1]# cat fun_ echo.sh
#!/bin/bash
get_users() {
	users= ( cat /etc/passwd| cut -d: -f1 )
	echo $users
}
#get_ users
#可以对拿到的函数结果进行遍历
user_list= get_users
index=1
for u in $user_list
do
	echo "The $index user is : $u"
	let index++
done

#2.retun实例

file=/ etc/ passwd
#定义文件
t_file(){
#函数判断
if[ -f $file ];then
	return 0
else
	return1
fi
#调用函数,并根据函数返回状态码进行输出
t_file && echo "该文件存在$file" || echo "该文件不存在$file"

1.数组基本概述

1.什么是数组
数组其实也算是变量,传统的变量只能存储一个值, 但数组可以存储多个值。
2.数组的分类
shell数组分为普通数组和关联数组

​ 普通数组:只能使用整数作为数组索引

[root@ssh02 scripts]# book=(linux nginx php)
[root@ssh02 scripts]# echo $book
linux
[root@ssh02 scripts]# echo ${book[2]}
php
[root@ssh02 scripts]# echo ${book[0]}
linux

book=(linux nginx php)   #普通数组
-----------------------
| linux | nginx | php |
-----------------------
|   0   |   1   |  2  |  #索引(下标)
-----------------------
PS:普通数组下标只能是整数

​ 关联数组:可以使用字符串作为数组索引

[root@ssh02 scripts]# declare -A info_2
[root@ssh02 scripts]# info_2=( [name]=oldxu [age]=18 [sex]=f )
[root@ssh02 scripts]# echo ${info_2[name]}
oldxu
[root@ssh02 scripts]# echo ${info_2[age]}
18

info=([name]=qjp [age]=18 [skill]=linux) 关联数组 python(字典)
--------------------
| qjp | 18 | linux |
--------------------
| name| age| skill |    #索引(下标)
--------------------    
PS: 关联数组的下标可以是字符串

#取出所有数据
[root@ssh02 scripts]# echo ${info_2[*]}
oldxu 18 f
[root@ssh02 scripts]# echo ${info_2[@]}
oldxu 18 f

#取出所有索引
[root@ssh02 scripts]# echo ${!info_2[@]}
name age sex

2.数组遍历与循环

1.数组的遍历与循环是啥?
其实就是使用对数组进行批量赋值,然后通过循环方式批量取出数组的值对其进行统计。
2.如果需要统计一个文件中某个字段出现的次数,怎么办?
思路就是:要统计谁就将谁作为数组的索引,注意仅支持关联数组。
3.如上的方式可以实现数组的赋值,但数组赋值后还需要遍历结果,才能完成统计需求,那么遍
历的方式有如下两种:
1.通过数组的个数进行遍用不推荐
2.通过数组的索引进行遍历(推荐)

1.普通数组赋值与遍历示例

[root@ssh02 scripts]# cat shuzu.sh 
#!/bin/bash

declare -A IP

while read file 
do
	test=$(echo $file | awk '{print $7}')
	let IP[$test]++
done<access.log

for i in ${!IP[@]}
do
	echo "索引是: $i,出现的次数: ${IP[$i]}"
done

posted @ 2019-11-04 20:17  执子人  阅读(159)  评论(0)    收藏  举报