【问题标题】:bash script to dynamically display array element based on user selection(s)基于用户选择动态显示数组元素的bash脚本
【发布时间】:2015-09-17 23:48:46
【问题描述】:

我必须编写一个 bash 脚本,让用户选择要显示的数组元素。

例如,数组有这些元素

ARRAY=(零一二三四五六)

我希望脚本能够在用户输入数组索引后打印出元素

假设用户输入(一行):1 2 6 5

那么输出将是:一二六五

输入的索引可以是单个(输入:0输出:)或多个(如上),输出将对应索引输入了

非常感谢任何帮助。

谢谢

【问题讨论】:

    标签: arrays bash


    【解决方案1】:
    ARRAY=(zero one two three four five six)
    for i in $@; do
        echo -n ${ARRAY[$i]}
    done
    echo
    

    然后像这样调用这个脚本:

    script.sh 1 2 6 5
    

    它会打印出来:

    one two six five
    

    【讨论】:

      【解决方案2】:

      您可能希望将关联数组用于通用解决方案,即假设您的键不只是整数:

      # syntax for declaring an associative array
      declare -A myArray
      # to quickly assign key value store
      myArray=([1]=one [2]=two [3]=three)
      # or to assign them one by one
      myArray[4]='four'
      # you can use strings as key values
      myArray[five]=5
      # Using them is straightforward
      echo ${myArray[3]} # three
      # Assuming input in $@
      for i in 1 2 3 4 five; do
          echo -n ${myArray[$i]}
      done
      # one two three four 5
      

      另外,请确保您使用的是 Bash4(版本 3 不支持它)。详情请见this answer and comment

      【讨论】:

      • 问题中没有需要关联数组的内容。
      • 同意,我编辑了答案以反映通用解决方案
      猜你喜欢
      • 2023-04-03
      • 1970-01-01
      • 2016-01-16
      • 1970-01-01
      • 1970-01-01
      • 2018-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多