数组

array

标签(空格分隔): Shell


普通数组

#定义数组
shell> colors=("\e[;30m" "\e[;31m" "\e[;32m" "\e[;33m" "\e[;34m" "\033[35m" "\033[36m" "\033[30m" "\033[36m" "\033[40m" "\033[41m" "\033[42m""\033[43m" "\033[44m" "\033[45m" "\033[46m")
# 数组的所有元素
shell> echo ${colors[@]}
\e[;30m \e[;31m \e[;32m \e[;33m \e[;34m \033[35m \033[36m \033[30m \033[36m \033[40m \033[41m \033[42m\033[43m \033[44m \033[45m \033[46m
# 数组的元素个数
shell> echo ${#colors[@]}
15
# 数组的元素的索引
shell> echo ${!colors[@]}
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
#获取某个元素的值
shell> echo ${colors[2]}
\e[;32m
# 从下标为0,往后2个元素的值
shell> echo ${colors[@]:0:2}
\e[;30m \e[;31m

#!/bin/bash
while read line
do
    hosts[++i]=$line
done 
#!/bin/bash
while read line
do
    user=`echo $line|awk -F":" '{print $1}' `
    hosts[++i]=$user
done 
#!/bin/bash
while :
do
        read -p "请输入图书名(q退出):" book
        if [ "$book" = "q" -o "$book"="" ];then
                break
        else
                books[++i]=$book
        fi 
done

for i in ${!books[@]}
do
        echo "$i: ${books[i]}"
done

关联数组

#!/bin/bash

declare -A sex # 定义一个关联数组
while read line
do
        gender=`echo $line|awk '{print $2}'`
        let sex[$gender]++
done 
#!/bin/bash


declare -A conn

states=`/usr/sbin/ss -an|grep ":80"|awk '{print $2}'`
for i in $states
do
    let conn[$i]++
done

for j in ${!conn[@]}
do
    echo "$j:${conn[$j]}"

done

你可能感兴趣的:(数组)