zoukankan      html  css  js  c++  java
  • shell脚本学习总结02--数组

    bash同时支持普通数组个关联数组,普通数组只能使用整数作为数组的索引,关联数组可以使用字符串作为数组的索引。

    数组的定义方法:

    在单行中使用一列值定义一个数组

    [root@new ~]# array1=(1 2 3 4 5 6)

    使用索引-值定义

    [root@new ~]# array2[0]="test1"
    [root@new ~]# array2[1]="test2"
    [root@new ~]# array2[2]="test3"

     使用key-value键值对

    [root@new ~]# fruits=([apple]=5 [orange]=3 [banana]=4)
    [root@new ~]# echo ${fruits[apple]}
    4

    打印数组元素:

    打印出数组指定索引的数组元素内容

    [root@new ~]# echo ${array2[0]}
    test1

    打印出数组中的所有值

    [root@new ~]# echo ${array2[*]}
    test1 test2 test3

    或者:

    [root@new ~]# echo ${array2[@]}
    test1 test2 test3

    打印出数组的长度

    [root@new ~]# echo ${#array2[*]}
    3

    截取数组-

    [root@new ~]# array=(0 1 2 3 4)
    [root@new ~]# echo ${array[*]:1:3}
    1 2 3

     更多用法参照--变量字符串的常用操作shell脚本学习总结05--变量与环境变量

    列出数组索引

    [root@new ~]# echo ${!array2[*]}
    0 1 2

     删除数组

    删除单个数组

    [root@new ~]# unset array2[0]
    [root@new ~]# echo ${array2[*]}
    test2 test3

    删除整个数组

    [root@new ~]# unset array2
    [root@new ~]# echo ${array2[*]}
    
    [root@new ~]# 

     脚本应用:

    [root@new sbin]# cat array.sh 
    #/bin/bash
    log=(`ls /var/log/httpd`)
    for((i=0;i<${#log[*]};i++))
    do
        echo "The $i log is ${log[i]}"
    done
    [root@new sbin]# sh array.sh 
    The 0 log is www.a.org-access_log
    The 1 log is www.a.org-error_log
    The 2 log is www.b.net-access_log
    The 3 log is www.b.net-error_log
  • 相关阅读:
    [转] STM32 FSMC学习笔记
    【转】嵌入式系统 Boot Loader 技术内幕
    mini2440 使用 JLink V8 直接烧写 Nor flash
    S3C6410移植uboot(一)
    2440的RTC时钟
    关闭2440 屏幕背光
    基于十级流水线的开立方根算法
    Visual Studio 2008配置SystemC开发环境
    Linux C 中字符串化操作符#
    linux 中 timeval结构体
  • 原文地址:https://www.cnblogs.com/zydev/p/5725319.html
Copyright © 2011-2022 走看看