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

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

问题描述

使用:

set -o nounset

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

  1. Having an indexed array like:

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

检查元素 1 是否设置的最短方法是什么?
我有时会使用以下内容:

What 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"

我想知道是否有首选.

如何处理非连续索引?

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

例如如何快速检查51是否已经设置?

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

如何处理关联数组?

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

例如如何快速检查key2是否已被使用?

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

推荐答案

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

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

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

基本上${array[key]+abc}的作用是

  • 如果设置了array[key],返回abc
  • 如果 array[key] 未设置,则不返回任何内容
  • if array[key] is set, return abc
  • if array[key] is not set, return nothing

<小时>参考资料:

  1. 参见参数扩展在 Bash 手册和小注

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

如果省略冒号,则操作符只测试[of 参数]

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

  • 这个答案实际上改编自这个 SO 问题的答案:如何判断一个字符串是否未在 bash shell 脚本中定义?

    <小时>

    一个包装函数:


    A wrapper function:

    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天全站免登陆