实际使用bash数组

dat*_*789 1 arrays bash shell

在阅读了如何在Bash中初始化数组并看到博客中提出的一些基本示例之后,其实际应用仍存在一些不确定性.一个有趣的例子可能是按升序排序 - 按随机顺序列出从A到Z的国家/地区,每个字母一个.

但在现实世界中,Bash阵列是如何应用的?它适用于什么?数组的常见用例是什么?这是我希望熟悉的一个领域.任何使用bash数组的冠军?请提供你的例子.

Wil*_*ill 5

在某些情况下,我喜欢在Bash中使用数组.

  1. 当我需要存储可能包含空格或$IFS字符的字符串集合时.

    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
    
    Run Code Online (Sandbox Code Playgroud)
    This is a sentence. 4 words.
    I like turtles. 3 words.
    This is a test. 4 words.
    
    Run Code Online (Sandbox Code Playgroud)
  2. 当我想存储键/值对时,例如,映射到长描述的短名称.

    declare -A NEWARRAY=(
         ["sentence"]="This is a sentence."
         ["turtles"]="I like turtles."
         ["test"]="This is a test."
    )
    
    echo ${NEWARRAY["turtles"]}
    echo ${NEWARRAY["test"]}
    
    Run Code Online (Sandbox Code Playgroud)
    I like turtles.
    This is a test.
    
    Run Code Online (Sandbox Code Playgroud)
  3. 即使我们只是存储单个"单词"项目或数字,数组也可以轻松计算和切片数据.

    # 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.
    
    Run Code Online (Sandbox Code Playgroud)

了解更多关于猛砸阵列在这里.请注意,只有Bash 4.0+支持我列出的每个操作(例如,关联数组),但链接显示哪些版本引入了什么.