Check if a Bash array contains a value

前端 未结 30 3006
执笔经年
执笔经年 2020-11-22 07:14

In Bash, what is the simplest way to test if an array contains a certain value?

30条回答
  •  面向向阳花
    2020-11-22 08:00

    Another one liner without a function:

    (for e in "${array[@]}"; do [[ "$e" == "searched_item" ]] && exit 0; done) && echo "found" || echo "not found"
    

    Thanks @Qwerty for the heads up regarding spaces!

    corresponding function:

    find_in_array() {
      local word=$1
      shift
      for e in "$@"; do [[ "$e" == "$word" ]] && return 0; done
      return 1
    }
    

    example:

    some_words=( these are some words )
    find_in_array word "${some_words[@]}" || echo "expected missing! since words != word"
    

提交回复
热议问题