Linux进阶bash笔记--关联数组

B站影视 2024-11-17 23:34 2

摘要:#!/usr/bin/env bashdeclare -A assoc_array=([key_string]=value \[one]="something" \[two]="another thing" \[ three ]='mind the blank

#!/usr/bin/env bashdeclare -A assoc_array=([key_string]=value \[one]="something" \[two]="another thing" \[ three ]='mind the blanks!' \[ " four" ]='count the blanks of this key later!' \[IMPORTANT]='SPACES DO ADD UP!!!' \[1]='there are no integers!' \[info]="to avoid history expansion " \[info2]="quote exclamation mark with single quotes" \)echo # just a blank lineecho now here are the values of assoc_array:echo ${assoc_array[@]}echo not that useful,echo # just a blank lineecho this is better:declare -p assoc_array # -p == printecho have a close look at the spaces above\!\!\!echo # just a blank lineecho accessing the keysecho the keys in assoc_array are ${!assoc_array[*]}echo mind the use of indirection operator \!echo # just a blank lineecho now we loop over the assoc_array line by lineecho note the \! indirection operator which works differently,echo if used with assoc_array.echo # just a blank linefor key in "${!assoc_array[@]}"; do # accessing keys using ! indirection!!!!printf "key: \"%s\"\nvalue: \"%s\"\n\n" "$key" "${assoc_array[$key]}"doneecho have a close look at the spaces in entries with keys two, three and four above\!\!\!echo # just a blank lineecho # just another blank lineecho there is a difference using integers as keys\!\!\!i=1echo declaring an integer var i=1echo # just a blank lineecho Within an integer_array bash recognizes artithmetic context.echo Within an assoc_array bash DOES NOT recognize artithmetic context.echo # just a blank lineecho this works: \${assoc_array[\$i]}: ${assoc_array[$i]}echo this NOT!!: \${assoc_array[i]}: ${assoc_array[i]}echo # just a blank lineecho # just a blank lineecho an \${assoc_array[i]} has a string context within braces in contrast to an integer_arraydeclare -i integer_array=( one two three )echo "doing a: declare -i integer_array=( one two three )"echo # just a blank lineecho both forms do work: \${integer_array[i]} : ${integer_array[i]}echo and this too: \${integer_array[\$i]} : ${integer_array[$i]}

如果您对我的文章有兴趣,我把我发布的文章都归档到我私人网站中去,欢迎访问 https://three-corner.xyz Corner 三的小角落 -- 首页 查阅之前的文章。

来源:广西客家人

相关推荐