Loop over tuples in bash?

后端 未结 12 1541
说谎
说谎 2020-12-04 21:00

Is it possible to loop over tuples in bash?

As an example, it would be great if the following worked:

for (i,j) in ((c,3), (e,5)); do echo \"$i and $         


        
12条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 21:24

    Use associative array (also known as dictionary/hashMap):

    declare -A pairs=(
      [c]=3
      [e]=5
    )
    for key in "${!pairs[@]}"; do
      value="${pairs[$key]}"
      echo "key is $key and value is $value"
    done
    

    Works for bash4.0+.


    If you need triples instead of pairs, you can use the more general approach:

    animals=(dog cat mouse)
    declare -A sound=(
      [dog]=barks
      [cat]=purrs
      [mouse]=cheeps
    )
    declare -A size=(
      [dog]=big
      [cat]=medium
      [mouse]=small
    )
    for animal in "${animals[@]}"; do
      echo "$animal ${sound[$animal]} and it is ${size[$animal]}"
    done
    

提交回复
热议问题