
현재 및 사용자 지정 디렉터리의 모든 파일 이름을 자동으로 읽은 다음 새로 생성된 도커 이미지 이름을 kubectl을 통해 찾은 yml 파일에 적용한 다음 두 배열에서 이미지 이름을 읽는 bash 스크립트를 작성하려고 합니다. 전체 레지스트리 이름 :
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=`...`
이렇게 하면 배열이 너무 많이 생성되지 않으며 명령 대체의 모든 출력이 배열의 요소 0에 할당됩니다. 실제 배열 할당 구문은 즉, 괄호와 요소를 별개의 단어로 사용하는 것입니다.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