bash array

1. declare

declare -a array
read -a array < input.txt

2. assignment

array[key]=value
array=(val1 val2 ... valN)

3. access

# the first element
${array[0]} <=> ${array[@]:0:1} <=> $array

# the entire elements
${array[@]} <=> ${array[*]}

# the first two elements
${array[@]:0:2} <=> ${array[0]} ${array[1]}

# the entire elements except the first one
${array[@]:1} <=> ${array[1]} ... ${array[N-1]}

# iterartion
for i in ${array[@]}

4. eliminate

unset array[0]
unset array

5.length

# length of the array
${#array[@]}

# length of the first element
${#array} <=> ${#array[0]}

6. index of the array

${!array[@]}

7. examples

$ awk 'BEGIN{FS=":";ORS=" "}{print $1}' /etc/passwd > users.list                                                          
$ cat users.list                                                                                                          
root bin daemon adm lp sync shutdown halt mail operator games ftp nobody systemd-timesync systemd-network systemd-resolve systemd-bus-proxy dbus tss unbound apache mysql mysql-proxy geoclue jetty derby cg redis mongodb                                
$ read -a array < users.list   

# show the details of an array
$ set | grep array                                                                                                        
array=([0]="root" [1]="bin" [2]="daemon" [3]="adm" [4]="lp" [5]="sync" [6]="shutdown" [7]="halt" [8]="mail" [9]="operator" [10]="games" [11]="ftp" [12]="nobody" [13]="systemd-timesync" [14]="systemd-network" [15]="systemd-resolve" [16]="systemd-bus-proxy" [17]="dbus" [18]="tss" [19]="unbound" [20]="apache" [21]="mysql" [22]="mysql-proxy" [23]="geoclue" [24]="jetty" [25]="derby" [26]="cg" [27]="redis" [28]="mongodb")  

# index
$ echo ${!array[@]}                                                                                                       
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28  

# length
$ echo ${#array[@]}
29

# delete array[5]
$ unset array[5]
$ echo ${#array[@]}
28

# delete array
$ unset array
$ echo ${#array}                                                                                                          
0                                                               
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值