本文連接配接 https://www.jianshu.com/p/8f2e13c5330d
一、數組 (array) 變量
定義和取值
數組中的值:
wukong bajie shaseng
值的索引号:
0 1 2
負數的索引号:
-3 -2 -1
數組的索引隻能是 整數
# 定義一個數組
var=(wukong bajie shaseng)
echo ${var[2]} //顯示數組中索引号為 2 的值,索引号從 0 開始
輸出 shaseng
echo ${var[*]} //顯示數組中所有的值
輸出 wukong bajie shaseng
定義數組,并且其值從指令的結果中擷取
# 把檔案中的每一行作為數組中的一個值
line=(`cat /etc/passwd`)
切片
普通字元串切片
# 擷取到 CPU 型号資訊,作為基礎資料進行處理
[[email protected] ~]# cpu=$(grep 'model name' /proc/cpuinfo |uniq|cut -d: -f2)
[[email protected] ~]# echo "|$cpu|"
| Intel(R) Xeon(R) Platinum 8163 CPU @ 2.50GHz|
[[email protected] ~]# echo ${cpu:1} # 從索引号 1 開始向後取值,取到最後
Intel(R) Xeon(R) Platinum 8163 CPU @ 2.50GHz
[[email protected] ~]# cpu=${cpu:1}
[[email protected] ~]# echo "|$cpu|"
|Intel(R) Xeon(R) Platinum 8163 CPU @ 2.50GHz|
數組切片
[[email protected] ~]# nums=(a b c d e)
[[email protected] ~]# echo ${nums[*]:2} # 從索引号 2 開始向後取值,取到最後
c d e
[[email protected] ~]# echo ${nums[*]:2:2} # # 從索引号 2 開始向後取值,取 2 個
c d
[[email protected] ~]#
循環數組
[[email protected] ~]# nums=(a b c d e)
[[email protected] ~]# for i in ${nums[*]}
> do
> echo $i
> done
a
b
c
d
e
二、declare 聲明關聯數組
數組的索引可以是 普通字元串
聲明關聯數組使用
A
選項
declare -A 數組名稱
1. 聲明
# 聲明關聯數組,數組名稱為 info
[[email protected] ~]$ declare -A info
2. 添加值
- 每次添加一個值,可以追加
示例:
[[email protected] ~]$ info["name"]="shark"
[[email protected] ~]$ info["age"]=18
[[email protected] ~]$ echo ${info["name"]} # 顯示索引對應的值
shark
[[email protected] ~]$ echo ${info["age"]}
18
- 一次添加是以的值,不可以追加,每次都會覆寫上次的值
每個值之間使用 空格 隔開
var=([key1]="value1" [key2]="value2")
示例:
[外鍊圖檔轉存失敗,源站可能有防盜鍊機制,建議将圖檔儲存下來直接上傳(img-mWhalANC-1626163535947)(assets/image-20200910101909271.png)]
删除
[[email protected] arry]# unset info[name]
[[email protected] arry]# echo ${!info[*]}
age
循環關聯數組
[[email protected] ~]# echo ${info[@]}
shark 18
[[email protected] ~]# for i in ${info[@]}
> do
> echo $i
> done
shark
18
[[email protected] ~]#