函数

函数的三种定义方式

#!/bin/sh

#直接定义
test1() {
echo "第一种定义方式"
}

#区别于第一种,多了function关键字
function test2() {
echo "第二种定义方式"
}

#区别于第二种,秘钥小括号
function test3 {
echo "第三种定义方式"
}
test1
test2
test3

案例1:统计一个文件的行数

  • 函数封装代码,使用while读取文件,并计数,然后输出文件行数
#!/bin/sh

File=/etc/passwd

function count(){
local i=0
while read line
do
let i++
done<$File
echo $i
}
count

案例2:脚本间互相调用函数

  • 执行的脚本test.sh
#!/bin/sh

. ./function.sh
fun
  • 调用的脚本function.sh]
#!/bin/sh

fun(){
    echo "function.sh"
}

数组

索引数组

赋值

[root@home ~]# array[0]=linux0
[root@home ~]# array[1]=linux1
[root@home ~]# array[2]=linux2
[root@home ~]# array=([0]=Linux4 [1]=Linux5 [2]=Linux6)
[root@home ~]# array=(Linux7 Linux8 Linux9)

输出键和值

[root@home ~]# array[0]=linux0
[root@home ~]# array[1]=linux1
[root@home ~]# array[2]=linux2
[root@home ~]# echo ${array[0]}
linux0
[root@home ~]# echo ${array[1]}
linux1
[root@home ~]# echo ${array[2]}
linux2
[root@home ~]# echo ${array[*]}
linux0 linux1 linux2
[root@home ~]# echo ${!array[*]}
0 1 2
[root@home ~]# echo ${array[@]}
linux0 linux1 linux2
[root@home ~]# echo ${!array[@]}
0 1 2

清除数组

[root@home ~]# array[0]=linux0
[root@home ~]# array[1]=linux1
[root@home ~]# array[2]=linux2
[root@home ~]# echo ${array[*]}
linux0 linux1 linux2
[root@home ~]# unset array
[root@home ~]# echo ${array[*]}

关联数组

  • 关联数组和索引数组的区别在键的内容和赋值时需要声明
#赋值前需要声明一个关联数组
#声明一个array的关联数组(awk中不需要定义关联数组)
declare -A array

赋值

[root@home ~]# declare -A array
[root@home ~]# array=([index0]=Linux0 [index1]=Linux1 [index2]=Linux2)
[root@home ~]# echo ${array[*]}
Linux0 Linux1 Linux2
[root@home ~]# echo ${!array[*]}
index0 index1 index2
[root@home ~]# array[index4]=Linux4
[root@home ~]# echo ${array[*]}
Linux4 Linux0 Linux1 Linux2
[root@home ~]# echo ${!array[*]}
index4 index0 index1 index2

遍历数组

案例1:使用for循环遍历数组

#!/bin/sh

array=(Linux7 Linux8 Linux9)

for i in ${array[*]}
do
echo $i
done

案例2:使用数组,统计文件中m,f的个数

  • test.txt
m
f
f
m
m
f
f
f
  • test.sh
#!/bin/sh

declare -A array

while read line
do
let array[$line]++
done<test.txt


for i in ${!array[*]}
do
echo $i,${array[$i]}
done

案例3:使用数组,统计/etc/passwd中,bash的种类出现的次数最后一列

#!/bin/sh

declare -A array

for i in `awk -F: '{print $NF}' /etc/passwd`
do
let array[$i]++
done

for i in ${!array[*]}
do
echo $i,${array[$i]}
done