
我正在嘗試編寫bash 腳本,它將自動讀取當前和自訂目錄中的所有文件名,然後將新建立的docker 映像名稱套用到透過kubectl 找到的yml 文件,然後從兩個陣列讀取映像名稱和完整登錄名稱:
declare -a IMG_ARRAY=`docker images | awk '/dev2/ && /latest/' | awk '{print $1}' | sed ':a;N;$!ba;s/\n/ /g'`
declare -a IMG_NAME=`docker images | awk '/dev2/ && /latest/' | awk '{print $1}' | awk -F'/' '{print $3}' | cut -f1 -d"." | sed ':a;N;$!ba;s/\n/ /g'`
IFS=' ' read -r -a array <<< "$IMG_NAME"
for element in "${array[@]}"
do
kubectl set image deployment/$IMG_NAME $IMG_NAME=$IMG_ARRAY --record
kubectl rollout status deployment/$IMG_NAME
done
兩個數組具有相同數量的索引。我的循環應該從 IMG_NAME 取得第一個索引,並將每個陣列索引放入 kubectl 指令中。目前它正在佔用整個數組......
答案1
declare -a IMG_ARRAY=`...`
這不會創建太多的數組,命令替換的所有輸出都被分配給數組的元素零。實際的數組賦值語法是,即帶有括號並且元素作為不同的單字。name=(elem1 elem2 ... )
您可以使用分詞將輸出分離為元素,但這仍然需要括號,並且您會受到IFS
通配符的影響。declare -a aaa=( $(echo foo bar) )
創建兩個元素foo
和bar
。請注意,它會根據單字之間的空格進行分割,而不僅僅是換行符。
在這裡使用mapfile
/readarray
可能會更好,因為它是明確用於將行讀取到數組的。命令列幫助文字 ( help mapfile
) 對此進行了描述:
mapfile: mapfile [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array]
Read lines from the standard input into an indexed array variable.
Read lines from the standard input into the indexed array variable ARRAY, or
from file descriptor FD if the -u option is supplied. The variable MAPFILE
is the default ARRAY.
答案2
我的理解是,您希望docker images
在兩個數組中獲得處理後的輸出,其中每個數組元素對應於處理後輸出的一行。
該腳本未經測試,因為我既不知道 的輸出,docker images
也不知道 的命令語法kubectl
。
mapfile -t IMG_ARRAY < <(docker images | awk '/dev2/ && /latest/' | awk '{print $1}' | sed ':a;N;$!ba;s/\n/ /g')
mapfile -t IMG_NAME < <(docker images | awk '/dev2/ && /latest/' | awk '{print $1}' | awk -F'/' '{print $3}' | cut -f1 -d"." | sed ':a;N;$!ba;s/\n/ /g')
total=${#IMG_NAME[*]}
for (( i=0; i<$(( $total )); i++ ))
do
kubectl set image deployment/$IMG_NAME[$i] $IMG_NAME[$i]=$IMG_ARRAY[$i] --record
kubectl rollout status deployment/$IMG_NAME[i]
done
看https://www.cyberciti.biz/faq/bash-iterate-array/和https://mywiki.wooledge.org/BashFAQ/005以獲得解釋。
代替
total=${#IMG_NAME[*]}
for (( i=0; i<$(( $total )); i++ ))
你也可以使用
for i in ${!IMG_NAME[@]}
看https://stackoverflow.com/questions/6723426/looping-over-arrays-printing-both-index-and-value