zoukankan      html  css  js  c++  java
  • shell普通数组与关联数组对比

    关联数组

    [root@centos17 shell]# cat shells_count.sh 
    #!/bin/bash
    #login shell counts 
    
    declare -A shells
    
    while read line
    do
    	type=`echo $line|awk -F":" '{print $NF}'`
    	let shells[$type]++
    done < /etc/passwd
    
    #echo ${!shells[@]} ${shells[@]}
    for i in ${!shells[@]} 
    do
    	printf "%-20s %3s
    " $i ${shells[$i]}		
    done
    [root@centos17 shell]# sh shells_count.sh 
    /sbin/nologin         25
    /bin/sync              1
    /bin/bash              4
    /sbin/poweroff         1
    /sbin/shutdown         1
    /sbin/halt             1
    /usr/sbin/poweroff     1
    [root@centos17 shell]# 
    

      

    普通数组

    [root@centos17 shell]# cat /etc/hosts
    127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
    ::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
    192.168.0.160 nas
    192.168.5.105 centos17
    [root@centos17 shell]# sh hosts.sh 
    1:127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
    2:::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
    3:192.168.0.160 nas
    4:192.168.5.105 centos17
    [root@centos17 shell]# cat hosts.sh
    #!/bin/bash
    #hosts display
    
    OLD_IFS=$IFS
    #IFS=$`
    `
    IFS=$'
    '
    
    for i in `cat /etc/hosts`
    do
    	hosts[++a]=$i
    done
    
    
    for j in ${!hosts[@]}
    do
    	echo "$j:${hosts[j]}" 或者echo "$j:${hosts[$j]}"
    done
    [root@centos17 shell]# 
    

     

    小结:

      普通数组:调用数组值时,${hosts[$j]}与${hosts[j]}等价,索引前无需添加$符号。

      关联数组:调用数组值时,只能使用${shells[$i]},索引前必须添加$符号。因为关联数组的索引不能为数字。

    
    

     

  • 相关阅读:
    Oracle(日期函数)
    Oracle(数值函数)
    Oracle(字符函数)
    Oracle(order by)
    Oracle(限定查询2)
    Oracle(限定查询1)
    Oracle其他简单查询
    Oracle简单语句查询
    SQLPlus
    解决方案
  • 原文地址:https://www.cnblogs.com/xiaofeng666/p/13769557.html
Copyright © 2011-2022 走看看