shell 如何将这三个条件合二为一?

7cwmlq89  于 2023-04-21  发布在  Shell
关注(0)|答案(1)|浏览(85)

我有一个JSON文件,它多次包含"threatLevel" : (an integer)。我grep JSON,看看它是否包含一个threatLevel,它匹配我的$THREAT_LEVEL变量中的任何东西,最多10(包括)。
我有下面的条件逻辑流,它在很大程度上完成了这项工作。

#!/bin/bash

FILE="${CI_PROJECT_DIR}/iq.results.json"

if [ -z ${THREAT_LEVEL+x} ]; then # Checks if THREAT_LEVEL is unset. If unset, no checks will be made.
    echo "THREAT_LEVEL is unset. The job will ignore checking the results of $FILE.";
    exit 0
elif ! [[ $THREAT_LEVEL =~ ^[0-9]+$ ]]; then # Checks that the THREAT_LEVEL is only a positive integer.
    echo "Error - Invalid THREAT_LEVEL: THREAT_LEVEL must be a positive integer. It is currently set to $THREAT_LEVEL."
    exit 1
elif [ "$THREAT_LEVEL" -lt 1 ] || [ "$THREAT_LEVEL" -gt 10 ]; then # Checks that the THREAT_LEVEL is only between 1 and 10.
    echo "Error - Invalid THREAT_LEVEL: THREAT_LEVEL must be between 1 and 10. It is currently set to $THREAT_LEVEL."
    exit 1
else
    echo "THREAT_LEVEL is currently set to $THREAT_LEVEL"
    if [ "$THREAT_LEVEL" -lt 10 ]; then # If the THREAT_LEVEL is less than 10, grep for anything between THREAT_LEVEL and 10 inclusive.
        if grep -q -E '"threatLevel" : (['"$THREAT_LEVEL"'-9]|10)' "$FILE"; then
            echo "Detected dependencies with Threat Level of $THREAT_LEVEL or above in $FILE. Failing job.";
            exit 1
        else   
            echo "No dependencies with Threat Level of $THREAT_LEVEL or above detected in $FILE. Job allowed to pass";
            exit 0
        fi
    else
        if grep -q -E '"threatLevel" : 10' "$FILE"; then # Else THREAT_LEVEL must be 10. Grep for 10.
            echo "Detected dependencies with Threat Level of 10 in $FILE. Failing job.";
            exit 1
        else   
            echo "No dependencies with Threat Level of 10 or above detected in $FILE. Job allowed to pass.";
            exit 0
        fi
    fi
fi

我觉得这两个elif语句可以结合起来。
第一个elif只检查变量是否是正整数,它不关心它是否大于10,它可以是1000,它不能是字符串或负数或小数等。
第二个elif是检查它福尔斯1-10之间(包括1和10)。
有没有一个解决方案同时满足这两个标准?

bihw5rsg

bihw5rsg1#

要测试THREAD_LEVEL是否为整数,我将执行以下操作

if [[ $THREAD_LEVEL == *[^0-9]* ]]
then
  echo Not an integer: "'$THREAD_LEVEL'"
else
  ...

这只是检查变量中是否有非数字。
为了测试有效范围,我将执行如下操作

if (( THREAD_LEVEL > 9 && THREAD_LEVEL != 0 ))
then
  echo Thread level must be an integer from 1 to 10
else 
  ...

然而,如果THREAD_LEVEL提供了一个前导零,这可能会失败。例如,将THREAD_LEVEL设置为09将产生错误消息 value too great for base,因为前导零将指示八进制数。因此,我建议首先通过删除前导零来清理THREAD_LEVEL。将所有内容放在一起,我们有:

shopt -s extglob
THREAD_LEVEL=${THREAD_LEVEL##+(0)} # Remove leading zeroes
if [[ $THREAD_LEVEL == *[^0-9]* ]]
then
  ;# We know here that THREAD_LEVEL is not a natural number
elif [[ -z $THREAD_LEVEL ]]
then
  ;# THREAD_LEVEL originally consisted only of zeroes
elif ((THREAD_LEVEL > 10 ))
  ;# THREAD_LEVEL is too large
else
  ;# THREAD LEVEL is OK
  ...
fi

请注意,这里需要 extglob 来使模式+(0)表示0的一次或多次出现。

相关问题