Check if a Bash array contains a value

前端 未结 30 2449
执笔经年
执笔经年 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:08

    The answer with most votes is very concise and clean, but it can have false positives when a space is part of one of the array elements. This can be overcome when changing IFS and using "${array[*]}" instead of "${array[@]}". The method is identical, but it looks less clean. By using "${array[*]}", we print all elements of $array, separated by the first character in IFS. So by choosing a correct IFS, you can overcome this particular issue. In this particular case, we decide to set IFS to an uncommon character $'\001' which stands for Start of Heading (SOH)

    $ array=("foo bar" "baz" "qux")
    $ IFS=$'\001'
    $ [[ "$IFS${array[*]}$IFS" =~ "${IFS}foo${IFS}" ]] && echo yes || echo no
    no
    $ [[ "$IFS${array[*]}$IFS" =~ "${IFS}foo bar${IFS}" ]] && echo yes || echo no
    yes
    $ unset IFS
    

    This resolves most issues false positives, but requires a good choice of IFS.

    note: If IFS was set before, it is best to save it and reset it instead of using unset IFS


    related:

    • Accessing bash command line args $@ vs $*

提交回复
热议问题