【问题标题】:Bash - Can't copy associative array if piping block output to commandBash - 如果管道块输出到命令,则无法复制关联数组
【发布时间】:2020-11-24 09:40:14
【问题描述】:

使用以下代码,如果管道传输到命令,我无法在 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 管道进行这项工作?

【问题讨论】:

    标签: bash shell pipe associative-array whiptail


    【解决方案1】:

    请您尝试以下方法:

    #!/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 ... 表达式,它在不使用管道的情况下将封闭的块保留在前台进程中。
    请注意,我已修改代码以显示百分比,使其看起来像这样。

    【讨论】:

      【解决方案2】:

      那是因为,正如man bash 所说

      管道中的每个命令都作为单独的进程执行(即,在子外壳中)。

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

      【讨论】:

        猜你喜欢
        • 2015-12-07
        • 1970-01-01
        • 1970-01-01
        • 2011-05-21
        • 2016-12-13
        • 1970-01-01
        • 1970-01-01
        • 2020-04-04
        相关资源
        最近更新 更多