函数

# 函数定义的方式
函数名(){   # 注意这里有空格
    	commands
}
function 函数名{
    commands
}

# 使用$1, $2, $3方式传参
func(){ echo "hello $1"}    # 调用 func lily
func2(){ echo "hello $*"}   # 传多个参数 func2 lili clerk mephy

# 注意函数传参和脚本传参不一样
num=$1   # 就需要外部传参

# 函数的返回值
return 只能返回 1-255的整数
echo 返回字符串
return 1  # $? 结果为1

数组

数组可以存多个值,根据下标输出值
tt=(aa bb cc dd )
echo ${tt}  # 输出第一个
echo ${tt[@]}  ${tt[*]}  # 都是输出全部
echo ${!tt[*]}  # 输出下标
# 普通数组 VS 关联数组
普通数组 tt=(linux windows   shell) # 下标只能是整数
关联数组 info=([name]=clerk [age]=18 [gender]=female )
取值: info[name]
# 定义关联数组
declare -A info
info=([name]=clerk [age]=18 [gender]=female )
# 取值
echo ${info[age]}
echo ${info[@]}
echo ${!info[@]}   # 取索引
# 取消关联数组
unset info
#################### 普通数组操作 ##############################
# 变量赋值-- 方式一
array[0]=linux
array[1]=python
# 变量赋值 -- 方式二
array2=(aa bb cc)
array(1 3 44 "linux shell" [20]=docker)  # 索引20对应的值为docker
# 赋值 -- 方式三
array4=(`cat /etc/passwd`)  # 一行行的赋值
# 取出值
declare -a|grep array
echo ${array[1]}
echo ${array[@]}  # 取所有
echo ${! array[@]}  # 取索引
echo ${#array[@]}  # 统计数组元素个数
    
############################ 关联数组操作 ###########################
1. 声明关联数组 
declare -A info
2. 赋值
info[name]=clerk  # 单个赋值
info=([age]=18 [gender]=female)  
3. 取值
echo ${info[name]}   
echo ${info[@]}   # 取所有
echo ${!info[@]}  #取索引
echo ${#info[@]}  # 看个数   
4. 查看
declare -A|grep info

数组的遍历与循环

# 通过数组的索引进行遍历
#!/usr/bin/bash
# 批量对数组进行赋值
i=0
while read line
do
	hosts[i++]=$line
done</etc/hosts
# 取出数组中的每一个元素和其索引
for i in ${!hosts[@]}
do 
	echo "索引和值分别为: $i , ${hosts[i]}"
done

使用关联数组统计文件中的男女性别

#!/usr/bin/bash
# 注意要先声明
declare -A info_sex
# 遍历文件
while read line
do
	sex=$(echo $line|awk '{print $2}')
	let info_sex[$sex]++	# 每循环一次就加一
done<gender.txt
# 遍历数组,取出所有
for i in ${!info_sex[@]}
do 
	echo $i , ${info_sex[$i]}
done
'''
将性别作为key, 出现的次数为value
let info_sex[$sex]++
'''

使用数组统计 /etc/passwd的shell 的数量

#!/usr/bin/bash
declare -A array_pass
while read line
do
	type=$(echo $line|awk -F ":" '{print $NF}')
	let array_pass[$type]++
done</etc/passwd

for i in ${!array_pass[@]}
do
	echo $i,  ${array_pass[$i]}

done

统计Nginx 日志IP访问次数

#!/usr/bin/bash
declare -A nginx_ip
while read line
do
        type=$(echo $line|awk '{print $1}')
        let nginx_ip[$type]++

done<log.log

for j in ${!nginx_ip[@]}
do
        echo $j  , ${nginx_ip[$i]}

done
#!/usr/bin/bash

declare -A tcp_status
ss_types=$(ss -an|awk '{print $2}')
for i in $ss_types
do
	let tcp_status[$i]++
done
for j in ${!tcp_status[@]}
do
	echo $j, $tcp_status[$j]
done
posted on 2019-08-24 19:18  Afrafre  阅读(411)  评论(0编辑  收藏  举报