Check if a Bash array contains a value

前端 未结 30 2747
执笔经年
执笔经年 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 07:50

    One-line check without 'grep' and loops

    if ( dlm=$'\x1F' ; IFS="$dlm" ; [[ "$dlm${array[*]}$dlm" == *"$dlm${item}$dlm"* ]] ) ; then
      echo "array contains '$item'"
    else
      echo "array does not contain '$item'"
    fi
    

    This approach uses neither external utilities like grep nor loops.

    What happens here, is:

    • we use a wildcard substring matcher to find our item in the array that is concatenated into a string;
    • we cut off possible false positives by enclosing our search item between a pair of delimiters;
    • we use a non-printable character as delimiter, to be on the safe side;
    • we achieve our delimiter being used for array concatenation too by temporary replacement of the IFS variable value;
    • we make this IFS value replacement temporary by evaluating our conditional expression in a sub-shell (inside a pair of parentheses)

提交回复
热议问题