shell入门之----数组

shell 编程-数组

普通数组:只能用整数作为数组的索引
关联数组:可以使用字符串作为数组的索引

数组定义
普通数组定义:
[root@newrain shell]# books=( linux shell awk sed )  
引用:
[root@newrain shell]# echo ${books[0]}
linux
[root@newrain shell]# echo ${books[1]}
shell
[root@newrain shell]# echo ${books[2]}
awk

关联数组需要提前声明
declare -A myarry1
[root@newrain shell]# declare -A myarry1
[root@newrain shell]# myarry1=([name]=newrain [sex]=man [age]=26) 
[root@newrain shell]# echo ${myarry1[name]}
newrain
[root@newrain shell]# echo ${myarry1[age]}
26
定义方法1:
    # declare -a myarry=(5 6 7 8) 
    # echo ${myarry[2]}
		显示结果为 7
定义方法2:
    # array=( one two three four five six )
    # array2=(tom jack alice)
    # array3=(`cat /etc/passwd`)
    # array4=(tom jack alice "bash shell")
    # array5=(1 2 3 4 5 6 7 "linux shell" [20]=saltstack)
定义方法3: 
#!/bin/bash 
area[11]=23 
area[13]=37 
area[51]="UFOs"
访问数组

当设置任何数组变量时,可以访问它

[root@newrain shell]# aa=(haha heihei baibai)
[root@newrain shell]# echo ${aa[0]} 
[root@newrain shell]# echo ${aa[@]} 
[root@newrain shell]# echo ${#aa[@]} 
[root@newrain shell]# echo ${!aa[@]}
//访问数组中的第一个元数 //访问数组中所有的元数 等同与echo ${aa[*]} //统计元数的个数
//统计索引

${array_name[index]} //引用

示例

#!/bin/bash
NAME[0]="BJ"
NAME[1]="SH"
NAME[2]="SZ"
NAME[3]="GZ"
NAME[4]="HZ"
NAME[5]="ZZ"
echo "First Index: ${NAME[0]}"
echo "Second Index: ${NAME[1]}"
echo "sixth Index: ${NAME[5]}"

输出结果为

 $./test.sh
First Index: BJ 
Second Index: SH 
sixth Index: ZZ

您可以访问数组中的所有项目通过以下方式之一:

${array_name[*]}
${array_name[@]}

示例

#!/bin/sh
NAME[0]="BJ"
NAME[1]="SH"
NAME[2]="SZ"
NAME[3]="GZ"
NAME[4]="HZ"
echo "First Index: ${NAME[*]}"
echo "Second Index: ${NAME[@]}"

输出结果

 $./test.sh
First Index: BJ SH SZ GZ HZ 
Second Index: BJ SH SZ GZ HZ

疑难点
shell数组中"*" 和 “@” 区别

关于在shell脚本中数组变量中 “*”跟 “@” 区别
“*”当变量加上“” 会当成一串字符串处理. 
“@”变量加上“” 依然当做数组处理. 
在没有加上“” 的情况下 效果是等效的.

示例

#!/usr/bin/env bash
array=(gz cloud 19)
echo "case 1"
for line in "${array[@]}"
do
		echo $line
done

echo "case 2"
for line in "${array[*]}"
do
		echo $line
done

echo "case 3"
for line in ${array[*]}
do
		echo $line
done

echo "case 4"
for line in ${array[@]}
do
		echo $line
done

执行结果

case 1
gz
cloud
19
case 2
gz cloud 19
case 3
gz
cloud
19
case 4
gz
cloud
19
遍历数组while
[root@newrain array]# cat array01.sh 
#!/bin/bash
#++ i 是先自加1后赋值;i ++ 是先赋值后自加1。 
while read line
do
        host[i++]=$line
done </etc/hosts
for i in ${!host[@]}
do
        echo "$i:${host[i]}"
done
遍历数组for
[root@newrain array]# cat array02.sh 
#!/bin/bash
IFS=''
for line in `cat /etc/hosts`
do
        host[j++]=$line
done
for  i in ${!host[@]}
do
        echo ${host[i]}
done 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值