Practical use of bash array

前端 未结 1 1766
离开以前
离开以前 2021-01-24 17:05

After reading up on how to initialize arrays in Bash, and seeing some basic examples put forward in blogs, there remains some uncertainties on its practical use. An interesting

1条回答
  •  深忆病人
    2021-01-24 17:11

    There are a few cases where I like to use arrays in Bash.

    1. When I need to store a collections of strings that may contain spaces or $IFS characters.

      declare -a MYARRAY=(
          "This is a sentence."
          "I like turtles."
          "This is a test."
      )
      
      for item in "${MYARRAY[@]}"; do
          echo "$item" $(echo "$item" | wc -w) words.
      done
      
      This is a sentence. 4 words.
      I like turtles. 3 words.
      This is a test. 4 words.
      
    2. When I want to store key/value pairs, for example, short names mapped to long descriptions.

      declare -A NEWARRAY=(
           ["sentence"]="This is a sentence."
           ["turtles"]="I like turtles."
           ["test"]="This is a test."
      )
      
      echo ${NEWARRAY["turtles"]}
      echo ${NEWARRAY["test"]}
      
      I like turtles.
      This is a test.
      
    3. Even if we're just storing single "word" items or numbers, arrays make it easy to count and slice our data.

      # Count items in array.
      $ echo "${#MYARRAY[@]}"
      3
      
      # Show indexes of array.
      $ echo "${!MYARRAY[@]}"
      0 1 2
      
      # Show indexes/keys of associative array.
      $ echo "${!NEWARRAY[@]}"
      turtles test sentence
      
      # Show only the second through third elements in the array.
      $ echo "${MYARRAY[@]:1:2}"
      I like turtles. This is a test.
      

    Read more about Bash arrays here. Note that only Bash 4.0+ supports every operation I've listed (associative arrays, for example), but the link shows which versions introduced what.

    0 讨论(0)
提交回复
热议问题