shell

shell数组学习[技术]

Bash中还可以使用数组变量,其赋值有两种:

(1) name = (value1 … valuen) 此时下标从0开始
(2) name[index] = value

数组下标的范围没有任何限制,同时也不必使用连续的分量.

[[email protected] ~]# A=(a b c def)

==================================================

//取全部元素
[[email protected] ~]# echo ${A[@]} 或者 echo ${A[*]}
a b c def

=================================================

//取第一个元素
[roo[email protected] ~]# echo ${A[0]}
a

=================================================

//取得数组元素的个数
[[email protected] ~]# echo ${#A[@]} 或者 echo ${#A[*]}
4

//取得元素3的长度,因为下标从0开始,所以元素3就是def
[[email protected] ~]# echo ${#A[3]}
3

==================================================

[[email protected] ~]# A[3]=wenzizone.cn //将第三个元素重新赋值
[[email protected] ~]# echo ${A[@]}
a b c wenzizone.cn

==================================================
//清除变量
[[email protected] ~]# unset A
[[email protected] ~]# echo ${A[@]}
<没有输出>
==================================================

//清空变量,即将值变为空
[[email protected] ~]# A=
[[email protected] ~]# echo ${A[@]}

<没有输出>
==================================================

[[email protected] ~]# A=B
[[email protected] ~]# B=C
[[email protected] ~]# unset $A 事实上所取消的变量是 B 而不是 A
[[email protected] ~]# echo $A
B
[[email protected] ~]# echo $B

<没有输出>
=======================示例================================
#! /bin/bash
cat 1.txt|while read line
do
        myarray=($line)
        echo ${#myarray[@]}
        for ((i=0;i<=${#myarray[@]};i++))
        do
                echo ${myarray[$i]}
        done
done

1.txt的内容是
# cat 1.txt
/usr/local/nagios abc 192.168.11.1 192.168.11.15
/usr/local/nagios def 192.168.12.1 192.168.12.15

程序运行结果

# ./tst.sh 
4
/usr/local/nagios
abc
192.168.11.1
192.168.11.15

4
/usr/local/nagios
def
192.168.12.1
192.168.12.15

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *