Wednesday, April 27, 2022

[SOLVED] Regex in IF statement not evaluated propertly BASH

Issue

I´m struggling with this simple statement in bash:

Basically I want that echo shows the message only if OPTION1 is "yes" or 1 and OPTION2 is different than "yes or 1"

The problem is that even if OPTION2 is an empty string is evaluated as TRUE.

#!/bin/bash

OPTION1="YES"
OPTION2=""

if [[ "${OPTION1}" =~ ^[Ys][Es][Ss]|[1] ]] && [[ ! "${OPTION2}" =~ ^[Yy][Ee][Ss]|[1] ]];then
    echo "EXECUTED"
fi

How i may modify this in order to make if statement failt if OPTION2 is an empty string?


Solution

The issue is that if $OPTION2 is empty, the match fails, and the ! thus makes the whole test succeed. Add a test for an empty string into the RE:

#!/usr/bin/env bash

# Turn on case-insensitive matching to tidy up the REs
shopt -s nocasematch

OPTION1="YES"
OPTION2=""

if [[ "${OPTION1}" =~ ^(yes|1)$ ]] && [[ ! "${OPTION2}" =~ ^(yes|1|)$ ]]; then
    echo "EXECUTED"
else
    echo "NOT EXECUTED"
fi

Alternatively, if $OPTION2 is empty, expand a value that does match the regular expression:

if [[ "${OPTION1}" =~ ^(yes|1)$ ]] && [[ ! "${OPTION2:-yes}" =~ ^(yes|1)$ ]]; then
    echo "EXECUTED"
else
    echo "NOT EXECUTED"
fi


Answered By - Shawn
Answer Checked By - Marie Seifert (WPSolving Admin)