debugging 为什么我的键值评估在bash中失败了?

dsekswqp  于 2023-06-06  发布在  其他
关注(0)|答案(1)|浏览(106)
#!/usr/bin/env bash
location=LOCATION
function status (){
    therestformat="%t(%f)%20%p"
    declare -A icons=(
        ["?"]  ="???" #unknown
        ["o"]  ="  " #sunny
        ["m"]  ="󰅟  " #partly cloudy
        ["mm"] ="󰅟󰅟 " #cloudy
        ["mmm"]="󰅟󰅟󰅟" #very cloudy
        ["="]  ="󰗈󰗈󰗈" #fog
        ["///"]="  " #heavy rain
        ["//"] =" " #heavy showers
        ["**"] ="󰜗  " #heavy snow
        ["*/"] ="󰜗 " #heavy snow showers
        ["/"]  ="  " #light rain
        ["."]  =" " #light showers
        ["x"]  ="l  " #light sleet
        ["x/"] ="l " #light sleet showers
        ["*"]  ="  " #light snow
        ["*/"] =" " #light snow showers
        ["/!/"]=" 󱐋" #thundery heavy rain
        ["!/"] ="󱐋" #thundery showers
        ["*!*"]="󰜗󱐋" #thundery snow showers
    )
    echo $(curl -s "wttr.in/$location?format=%x")
    conditionplain=$(curl -s "wttr.in/$location?format=%x")
    conditionicon=${icons[conditionplain]}
    therest=$(curl -s "wttr.in/$location?format=$therestformat")
    echo "$therest ${icons[conditionplain]}"
}
function leftclick () {
    curl -s "wttr.in/$location" | less -R
}
function rightclick () {
    curl -s "v2.wttr.in/$location" | less -R
}

case "$1" in
    s) status ;;
    l) leftclick ;;
    r) rightclick ;;
esac

巴斯今天给了我一个很奇怪的虫子curl -s wttr.in/LOCATION?format=%x肯定会返回该表中的一个条件,但应用conditionicon=${icons[conditionplain]}会得到一个空字符串。
我已经尝试过使用引号、方括号等,但错误仍然存在。

c2e8gylq

c2e8gylq1#

问题是等号前面的空格:

["?"]  ="???" #unknown

较新版本的bash将["?"]视为键,将="???"视为值,而不是您预期的????。此行为在the manual中记录如下:
当赋值给关联数组时,复合赋值中的单词可以是赋值语句(需要下标),也可以是被解释为交替键和值序列的单词列表:name=(key1 value1 key2 value2 … )。这些处理与name=( [key1]=value1 [key2]=value2 … )相同。
所以要么去掉空格

["?"]="???" #unknown

或使用替代形式

"?"  "???" #unknown

相关问题