Bash - 如果管道块输出到命令,则无法复制关联数组

Bash - Can't copy associative array if piping block output to command

使用以下代码,如果管道到命令,我无法在 Bash 中克隆关联数组。我正在使用 Whiptail 来显示进度条:

#!/bin/bash 

declare -Ar ARR1=(
[a]='asdf'
[b]='qwerty'
[c]='yuio'
)

declare -A ARR2=()

clone() {
    {
        for key in "${!ARR1[@]}"; do
            ARR2[$key]="${ARR1[$i]}"

            echo "10"  # Hardcoded percentage for Whiptail
        done
    } | whiptail --gauge "Cloning" 6 60 0
}

clone

for key in "${!ARR2[@]}"; do
  echo "$key"
  echo "${ARR2[$i]}"
done

卸下 Whiptail 烟斗:

#!/bin/bash 

declare -Ar ARR1=(
[a]='asdf'
[b]='qwerty'
[c]='yuio'
)

declare -A ARR2=()

clone() {
    {
        for key in "${!ARR1[@]}"; do
            ARR2[$key]="${ARR1[$i]}"

            echo "10"  # Hardcoded percentage for Whiptail
        done
    }
}

clone

for key in "${!ARR2[@]}"; do
  echo "$key"
  echo "${ARR2[$i]}"
done

有没有办法让它与 Whiptail 管道一起工作?

那是因为,正如man bash所说

Each command in a pipeline is executed as a separate process (i.e., in a subshell).

子shell 环境中的更改不会传播到父 shell。

请您尝试以下操作:

#!/bin/bash

declare -Ar ARR1=(
    [a]='asdf'
    [b]='qwerty'
    [c]='yuio'
)

declare -A ARR2=()

clone() {
    {
        n=${#ARR1[*]}                   # number of items
        for key in "${!ARR1[@]}"; do
            ARR2[$key]="${ARR1[$key]}"
            (( i++ ))                   # increment a counter
            echo $(( 100 * i / n ))     # percentage
            sleep 1                     # wait for 1 sec
        done
    } > >(whiptail --gauge "Cloning" 6 60 0)
}

clone

for key in "${!ARR2[@]}"; do
    echo "$key"
    echo "${ARR2[$key]}"
done

关键是 } > >(whiptail ... 表达式,它在不使用管道的情况下将封闭块保留在前台进程中。
请注意,我已修改代码以显示百分比,使其看起来像那样。