Home > Back-end >  Regex in IF statement not evaluated propertly BASH
Regex in IF statement not evaluated propertly BASH

Time:04-27

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?

CodePudding user response:

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

CodePudding user response:

You can check that OPTION2 is not an empty string with [[ ! -z "${OPTION2}" ]]

#!/bin/bash

OPTION1="YES"
OPTION2=""

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