為什麼這個迴圈中的 printf 語句輸出的陣列是亂序的?

為什麼這個迴圈中的 printf 語句輸出的陣列是亂序的?

當我執行以下程式碼時,printf 語句的輸出似乎顯示數組無序。在宣告語句中,來源項在目標項之前聲明,而在輸出中則相反。

YELLOW=$'\e[93m'
declare -A OP=( [Description]="remote to destination" [Source]="/var/www" [Destination]="/foo/bar" [Log]="my.log" [Email]="me@here" );

NO_COLS=`tput cols`
COLS_PER_COL=$(($NO_COLS/3))
PRINT_FORMAT="%"$COLS_PER_COL"s%""s\n"

for i in "${!OP[@]}"; do
    printf $PRINT_FORMAT "$i :" " $YELLOW${OP[$i]}$ENDCOL"
done ;

輸出看起來像

         Description : remote to destination
         Destination : /foo/bar
              Source : /var/www
                 Log : my.log
               Email : me@here

誰能告訴我這裡發生了什麼事?或者我如何根據數組聲明實現正確的順序?

答案1

(和其他語言)中的關聯數組bash不會保留聲明中元素的順序。

您可以新增另一個關聯數組來追蹤聲明的順序:

YELLOW=$'\e[93m'
declare -A OP=( [Description]="remote to destination"
                [Source]="/var/www"
                [Destination]="/foo/bar"
                [Log]="my.log"
                [Email]="me@here" )

declare -A IP=( [1]="Description"
                [2]="Source"
                [3]="Destination"
                [4]="Log"
                [5]="Email" );

NO_COLS="$(tput cols)"
COLS_PER_COL="$((NO_COLS/3))"
PRINT_FORMAT="%${COLS_PER_COL}s%s\n"

for i in "${!IP[@]}"; do
  k=${IP[$i]}
  printf "$PRINT_FORMAT" "$k :" " $YELLOW${OP[$k]}$ENDCOL"
done

相關內容