shell 數組使用簡介


數組簡介

bash 只提供一維數組,並且沒有限定數組的大小。類似與C語言,數組元素的下標由0開始編號。獲取數組中的元素要利用下標。下標可以是整數或算術表達式,其值應大於或等於 0。用戶可以使用賦值語句對數組變量賦值。

數組賦值

  • 下標賦值
$ students[0]=Jack
$ students[1]=Alex
$ students[2]=Amy

也可以使用declare顯式聲明一個數組:

$ declare -a 數組名
  • 直接賦值
$ students=(Jack Alex Amy)
或
$ declare -a studentds=(Jack Alex Amy)
  • 命令賦值
    命令的輸出格式如下
$ ls
Desktop   Downloads  Pictures  Templates  virtualenv  
$ arr=($(ls))
  • 字典賦值
    可以通過declare -A命令聲明字典
$ declare -A dict=([key1]=val1 [key2]=val2)

訪問數組

創建數組
$ students=(Jack Alex Amy)
  • 通過下標訪問
$ echo ${students[0]}
Jack
$ echo ${students[1]}
Alex
$ echo ${students[2]}
Amy
  • 列出所有元素
$ echo ${students[@]}
Jack Alex Amy
或
$ echo ${students[*]}
Jack Alex Amy

@ 符號與 * 符號均可以列出所有元素

數組的其它操作

  • 獲取數組長度
$ echo ${#students[@]}
3
  • 打印數組下標
$ echo ${!students[@]}
0 1 2

也可以打印字典的key 值

$ declare -A dict=([key1]=val1 [key2]=val2)
$ echo ${!dict[@]}
key2 key1
  • 刪除數組
$ unset 數組名


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM