一、數組定義
數組是Shell中的變數類型之一,它可以存儲多個值,並且這些值可以是不同類型的。在Shell中,數組下標從0開始計數。定義數組變數時使用「數組名=(value1 value2 … valuen)」的方式,其中value1、value2、…、valuen表示數組中所存儲的值。
#!/bin/bash # 定義一個數字數組 num_array=(1 2 3 4 5) # 定義一個字元串數組 str_array=("a" "b" "c" "d" "e")
二、數組訪問
訪問數組元素時,需要通過下標來進行訪問。使用${數組名[下標]}的方式來獲取數組中指定下標對應的值。也可以使用@或*來獲取數組中的所有元素。
#!/bin/bash # 定義一個數字數組 num_array=(1 2 3 4 5) # 獲取數組中下標為2的元素 echo ${num_array[2]} # 獲取數組中所有元素 echo ${num_array[@]}
三、數組長度
獲取數組長度可以使用#操作符,例如「${#數組名[@]}」可以獲取數組中元素的個數。
#!/bin/bash # 定義一個數字數組 num_array=(1 2 3 4 5) # 獲取數組長度 echo ${#num_array[@]}
四、數組遍歷
遍曆數組需要使用循環結構。可以使用for循環,也可以使用while循環。實現方式如下:
#!/bin/bash # 定義一個數字數組 num_array=(1 2 3 4 5) # for循環遍曆數組中的元素 for num in ${num_array[@]} do echo $num done # while循環遍曆數組中的元素 i=0 while [ $i -lt ${#num_array[@]} ] do echo ${num_array[i]} i=$((i+1)) done
五、數組操作
數組的操作包括添加元素、刪除元素、修改元素等。可以使用+=操作符向數組末尾添加元素,使用unset命令刪除指定下標的元素,使用[下標]=value來修改指定下標的元素。
#!/bin/bash # 定義一個數字數組 num_array=(1 2 3 4 5) # 增加元素 num_array+=(6) echo ${num_array[@]} # 刪除元素 unset num_array[2] echo ${num_array[@]} # 修改元素 num_array[1]=0 echo ${num_array[@]}
以上是關於數組的一些常用操作,通過數組可以方便的對多個元素進行批量操作,對於一些需要對多個變數進行操作的場景非常有用。
完整代碼示例:
#!/bin/bash #定義一個數字數組 num_array=(1 2 3 4 5) echo ${num_array[@]} #獲取數組長度 echo ${#num_array[@]} #訪問數組中指定下標對應的值 echo ${num_array[2]} #使用@或*來獲取數組中的所有元素 echo ${num_array[@]} #循環遍曆數組中的元素 for num in ${num_array[@]} do echo $num done # while循環遍曆數組中的元素 i=0 while [ $i -lt ${#num_array[@]} ] do echo ${num_array[i]} i=$((i+1)) done #增加元素 num_array+=(6) echo ${num_array[@]} #刪除元素 unset num_array[2] echo ${num_array[@]} #修改元素 num_array[1]=0 echo ${num_array[@]}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/227282.html