I have a JSON file, which contains "threatLevel" : (an integer)
multiple times.
I grep the JSON to see if it contains a threatLevel which matches anything from my $THREAT_LEVEL variable, up to 10 (inclusive).
I have the following conditional flow of logic, which for the most part does the job.
#!/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
I feel like both elif statements can be combined.
The first elif is only checking that the variable is a positive integer. It doesn't care if it's above 10, it could be 1000, it just can't be a string or a minus number or a decimal etc.
The second elif is the one which checks that it falls between 1-10 inclusively.
Is there a solution which meets both criteria?