检查索引或数组中的一个关键的最简单的方法? [英] Easiest way to check for an index or a key in an array?

查看:186
本文介绍了检查索引或数组中的一个关键的最简单的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用:

set -o nounset

1)有一个索引数组,如:

1) Having an indexed array like:

myArray=( "red" "black" "blue" )

这是检查是否元素1设置最短的方法是什么?结果
我有时会使用以下命令:

Which is the shortest way to check if element 1 is set?
I sometimes use the following:

test "${#myArray[@]}" -gt "1" && echo "1 exists" || echo "1 doesn't exist"

我想知道是否有pferred一个$ P $。
结果
结果
2)如何处理非连续的索引?

I would like to know if there's a preferred one.

2) How to deal with non-consecutive indexes?

myArray=()
myArray[12]="red"
myArray[51]="black"
myArray[129]="blue"

如何快速检查五一已被设置为例子吗?
结果
结果
3)如何处理关联数组?

How to quick check that '51' is already set for example?

3) How to deal with associative arrays?

declare -A myArray
myArray["key1"]="red"
myArray["key2"]="black"
myArray["key3"]="blue"

如何快速检查键2已用于例子吗?
结果
结果
谢谢

How to quick check that 'key2' is already used for example?

Thanks

EDITED 结果
最简单的方法似乎对我说:

EDITED
The simplest way seems to me:

if test "${myArray['key_or_index']+isset}"
    then
        echo "yes"
    else
        echo "no"
fi;

这同时适用于索引和关联数组。有没有一套-o nounset显示错误。结果
由于doubleDown为headup。

This works for both indexed and associative arrays. No errors shown with set -o nounset.
Thanks to doubleDown for the headup.

推荐答案

要检查元素设置(适用于索引和关联数组)

To check if the element is set (applies to both indexed and associative array)

[ ${array[key]+abc} ] && echo "exists"

基本上什么 $ {数组[键] + ABC} 所做的就是


  • 如果阵列[关键] 设置,返回 ABC

  • 如果阵列[关键] 没有设置,返回任何

  • if array[key] is set, return abc
  • if array[key] is not set, return nothing



参考文献:


References:


  1. 请参见参数扩展猛砸手册和在稍微注意一下

  1. See Parameter Expansion in Bash manual and the little note

如果结肠被省略,操作者仅测试生存[中的参数的]

if the colon is omitted, the operator tests only for existence [of parameter]

这答案其实是改编自答案为这太问题:<一href=\"http://stackoverflow.com/questions/228544/how-to-tell-if-a-string-is-not-defined-in-a-bash-shell-script\">How判断一个字符串是不是在bash shell脚本定义?

  • This answer is actually adapted from the answers for this SO question: How to tell if a string is not defined in a bash shell script?

    一个包装函数:

    exists(){
      if [ "$2" != in ]; then
        echo "Incorrect usage."
        echo "Correct usage: exists {key} in {array}"
        return
      fi   
      eval '[ ${'$3'[$1]+muahaha} ]'  
    }
    

    例如

    if ! exists key in array; then echo "No such array element"; fi 
    

    这篇关于检查索引或数组中的一个关键的最简单的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆