英文:
Why is my key-value evaluation failing in bash?
问题
Bash今天给我一个非常奇怪的错误。
curl -s wttr.in/LOCATION?format=%x
明确返回了表格中的一个条件,但应用 conditionicon=${icons[conditionplain]}
给我一个看起来是空字符串的东西。
我已经尝试过更改引号、括号等等 - 但错误仍然存在。
英文:
#!/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
Bash is giving me a really weird bug today.
curl -s wttr.in/LOCATION?format=%x
definitely returns a condition in that table, but applying conditionicon=${icons[conditionplain]}
gives me what appears to be an empty string.
I've tried messing with quotes, brackets, etc - but the error persists.
答案1
得分: 1
问题出在等号前面的空格:
["?"] ="???" #unknown
新版本的bash将["?"]
视为键,="???"
视为值,而不是你预期的?
和???
。这个行为在手册中有记录,如下所示:
> 当赋值给关联数组时,复合赋值中的单词可以是赋值语句,其中需要子脚本,或者是一系列单词,被解释为交替的键和值的序列:name=(key1 value1 key2 value2 … )
。这些与name=( [key1]=value1 [key2]=value2 … )
的形式相同。
因此,要么删除空格
["?"]="???" #unknown
要么使用备用形式
"?" "???" #unknown
英文:
The problem is the space preceding the equals sign:
["?"] ="???" #unknown
Newer versions of bash consider ["?"]
the key and ="???"
the value instead of ?
and ???
as you intended. This behavior is documented in the manual as follows:
> When assigning to an associative array, the words in a compound assignment may be either assignment statements, for which the subscript is required, or a list of words that is interpreted as a sequence of alternating keys and values: name=(key1 value1 key2 value2 … )
. These are treated identically to name=( [key1]=value1 [key2]=value2 … )
.
So either remove the space
["?"]="???" #unknown
or use the alternate form
"?" "???" #unknown
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论