zoukankan      html  css  js  c++  java
  • shell数组

    数组是特殊的变量,普通变量可以支持切片

    a=sum_abc.mail.cn

    echo ${a:5:3}

    abc 

    普通数组只能使用整数做为数组索引,关联数组可以使用字符串做为数组索引

    普通数组

    apples=(linux shell wps fox wp)

    linux  shell  wps  fox  wp

    0    1    2   3      4  索引(下标)

    array3=(1 3 5 8 "linux" [15]=static)    #可以跳索引赋值

    关联数组

    declare   -A   info    #shell默认不支持关联数组,需要使用-A手动声明

    info=([name]=huya [sex]=w  [age]=20  [skill]=fun)

    echo ${info[name]}

    echo ${info[sex]}

    查看数组

    echo  ${info[@]}      #@查看数组的内容

    huya w 20 fun

    echo  ${!info[@]}      #!查看数组的索引(重要),可以通过数组的索引进行遍历

    name sex age skill

    echo ${#info[@]}    ##查看数组的元素个数

    4

    例证:数组赋值及遍历

    vim   array.sh

    #!/usr/bin/bash

    while read line    #对行的循环调用,使用while(默认读取一行)

    do

      array[++i]=$line

    done < $1

    echo "The first array is ${array[1]}"

    echo

    for i in ${!array[@]}      # ${!array[@]}取的数组的索引

    do

      echo "The $i : ${array[$i]}"

    done

    sh -vx array.sh  /etc/hosts

    vim  count_sex.sh

    #!/usr/bin/bash

    #count sex

    #v1 by xfeng

    declare -A  sex

    while read line

    do

      type=`echo $line | awk '{print $2}'`

      let sex[$type]++      #将type当做数组的索引,sex[$type]做为数值的值,进行自增运算(类似与i++)

    done < sex.txt

    for i in ${!sex[@]}

    do

      echo "$i:${sex[$i]}"

    done

    注意:

    i++ 与++i的区别,对于表达式来说,结果不同;对于变量i来说,结果相同,没有区别。

    使用数组统计linux的登陆shell

     vim count_shell.sh

    #!/usr/bin/bash
    #count shells

    declare -A shells

    while read line
    do
    type=`echo $line |awk -F: '{print $NF}'`
    let shells[$type]++
    done < /etc/passwd

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

    bash -n count_shell.sh
    chmod +x count_shell.sh
    ./count_shell.sh

    /sbin/nologin: 19
    /bin/sync: 1
    /bin/bash: 1
    /sbin/shutdown: 1
    /sbin/halt: 1

    提示:统计数据,把要统计的对象作为数组的索引

  • 相关阅读:
    obs问题记录
    树莓派数字识别相关资料
    Focus Event
    跨浏览器的事件对象
    浅谈Javascript事件模拟
    浅谈Javascript鼠标和滚轮事件
    UI Events
    IE事件对象(The Internet Explorer Event Object)
    eclipse 调试nodejs 发生Failed to connect to standalone V8 VM错误的解决方案
    关于couldn't connect to server 127.0.0.1 shell/mongo.js:84 exception: connect failed 问题
  • 原文地址:https://www.cnblogs.com/xiaofeng666/p/12244879.html
Copyright © 2011-2022 走看看