【shell】判断一个字符串是否在数组中

1. 方法一:${JAVA_ALLOWED_VERSIONS[*]} =~ "$JAVA_VERSION" 

JAVA=`type -p java`
JAVA_ALLOWED_VERSIONS=( "1.8" "11" )
# Work out the JAVA version we are working with:
#JAVA_VERSION=$($JAVA -version 2>&1 | sed -n ';s/.* version "\([0-9]\{2,\}\|[0-9]\.[0-9]\)\..*".*/\1/p;')
JAVA_VERSION=$($JAVA -version 2>&1 | sed -n ';s/.* version "\([0-9]*\)\.\([0-9]*\)\..*".*/\1\.\2/p;')
echo $JAVA_VERSION
echo ${JAVA_ALLOWED_VERSIONS[*]}



if [[ ${JAVA_ALLOWED_VERSIONS[*]} =~ "$JAVA_VERSION" ]]; then
    echo "Correct java version found" >&2
else
    echo "Found an incorrect Java version" >&2
    echo "Java version found:" >&2
    echo $($JAVA -version) >&2
    echo "Aborting" >&2
    exit 1
fi

2. 方法二:${JAVA_ALLOWED_VERSIONS[@]} =~ "$JAVA_VERSION" 

JAVA=`type -p java`
JAVA_ALLOWED_VERSIONS=( "1.8" "11" )
# Work out the JAVA version we are working with:
#JAVA_VERSION=$($JAVA -version 2>&1 | sed -n ';s/.* version "\([0-9]\{2,\}\|[0-9]\.[0-9]\)\..*".*/\1/p;')
JAVA_VERSION=$($JAVA -version 2>&1 | sed -n ';s/.* version "\([0-9]*\)\.\([0-9]*\)\..*".*/\1\.\2/p;')
echo $JAVA_VERSION
echo ${JAVA_ALLOWED_VERSIONS[@]}



if [[ ${JAVA_ALLOWED_VERSIONS[@]} =~ "$JAVA_VERSION" ]]; then
    echo "Correct java version found" >&2
else
    echo "Found an incorrect Java version" >&2
    echo "Java version found:" >&2
    echo $($JAVA -version) >&2
    echo "Aborting" >&2
    exit 1
fi

 

参考链接:

https://www.jianshu.com/p/4baf0b324dac

posted @ 2022-03-31 15:51  代码诠释的世界  阅读(1226)  评论(0编辑  收藏  举报