[root@localhost ~]# vim array-for.sh #!/bin/bash#OLD_IFS=$IFS#IFS=$'\n'for line in `cat/etc/hosts`
do
hosts[i++]=$line
done
for i in ${!hosts[@]}doecho"$i---"echo"${hosts[$i]}"
done
#IFS=$OLD_IFS[root@localhost ~]# bash array-for.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
---解决for循环的空格分割问题:IFS=$'\n'---[root@localhost ~]# vim array-for.sh #!/bin/bash
OLD_IFS=$IFS#讲旧的分隔符备份
IFS=$'\n'#定义for的分隔符是换行符for line in `cat/etc/hosts`
do
hosts[i++]=$line
done
for i in ${!hosts[@]}doecho"$i---"echo"${hosts[$i]}"
done
IFS=$OLD_IFS#将分隔符还原,便于脚本后方的for使用
案例3:数组统计性别
---1.定义性别文本---[root@localhost ~]# vim sex.txt
jack m
alice f
tom m
---2.定义脚本统计性别---[root@localhost ~]# vim sex.sh#!/bin/bash
declare -A sex
while read line
dotype=`echo$line|awk '{print $2}'`
let sex[$type]++
done < sex.txt
for i in ${!sex[@]}doecho"$i : ${sex[$i]}"
done
---3.测试脚本---[root@localhost ~]# bash sex.sh
f : 1
m : 2
案例4:使用数组统计,用户shell的类型和数量
[root@localhost ~]# vim passwd.sh #!/bin/bash
declare -A shells
while read ll
dotype=`echo$ll| awk -F: '{print $NF}'`
let shells[$type]++
done < /etc/passwd
for i in ${!shells[@]}doecho"$i : ${shells[$i]}"
done
[root@localhost ~]# bash passwd.sh /sbin/nologin : 39
/bin/sync : 1
/bin/false : 1
/bin/bash : 6
/sbin/shutdown : 1
/sbin/halt : 1
--- 需求 ---
编写循环脚本,功能菜单
provide these tools:
show disk info(d)
show mem info(m)
show cpu info(c)
quit(q)--- 思路 ---
1.编写菜单和判断
2.添加循环
3.添加函数
--- 演示1 ---[root@localhost ~]# vim menu.sh#!/bin/bash
show_menu(){cat << EOF
provide these tools:
show disk info(d)
show mem info(m)
show cpu info(c)
quit(q)
EOF
}while :
do
show_menu
read -p "Input choice: " choice
case $choice in
d)echo"===========disk info=============="
df -hT
;;
m)echo"==========meme info==============="
free -m
;;
c)echo"==========cpu info================="
uptime
;;
q)break;;*)
show_menu
;;
esac
done
4.2示例2:阶乘函数(传参)
--- 需求 ---
制作函数用于阶乘
--- 思路 ---
1.了解阶乘概念
2.定义函数
3.引用函数
--- 演示 ---[root@localhost ~]# vim factorial.sh#!/bin/bash
fun(){
factorial=1
for((i=1;i<=$1;i++))#等同于for i in `seq $i`do
factorial=$[$factorial*$i]
done
echo"$1 阶乘: $factorial"}
fun $1
4.3示例3:函数传参 数组传参
--- 1.阶乘脚本,通过数组给函数传参
[root@localhost ~]# vim array3.sh #!/bin/bash
num=(1 2 3)
num2=(4 5 6)
array(){
factorial=1
for i in $*do
factorial=$[factorial*$i]
done
echo$factorial}
array ${num[*]}
array ${num2[*]}--- 2.数组好处在于多个数组时传参效率增高 ---
4.4示例4:函数结果 赋予数组
--- 1.通过函数输出到数组 ---[root@localhost ~]# vim array4.sh#!/bin/bash
num=(1 2 3)
array(){for i in $*do
outarray[j++]=$[$i+5]
done
echo"${outarray[*]}"}
result=`array ${num[*]}`
echo ${result[*]}--- 2.函数不仅可以从数组中调取值,还可以赋予数组值