Practical use of bash array

2019-03-01 11:42发布

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 example perhaps would be to sort in ascending order -- list countries from A to Z in random order, one for each letter.

But in the real world, how is a Bash array applied? What is it applied to? What is the common use case for arrays? This is one area I am hoping to be familiar with. Any champions in the use of bash arrays? Please provide your example.

1条回答
Bombasti
2楼-- · 2019-03-01 12:26

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.

查看更多
登录 后发表回答