系统相关
首页 > 系统相关> > 【shell】判断一个字符串是否在数组中

【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

标签:VERSION,shell,JAVA,VERSIONS,echo,version,数组,ALLOWED,字符串
来源: https://www.cnblogs.com/fireblackman/p/16082227.html