Search code examples
regexbashif-statementrhel

IF statement not working in RHEL 6 (workd in RHEL 5)


I have a simple if statement that works fine in RHEL 5, but for some inexplicable reason, fails in RHEL 6:

if [[ ! $1 =~ "(one|two|three)" ]] ; then
    echo -e "\n***Invalid number"
    usage
    exit 1
else
    action=$1
fi  

I can use a case statement which works fine or re-write it but more than anything, I'm curious as to what has changed, assuming it is the version of RHEL and not something else?


Solution

  • regex must not not be quoted in newer BASH (starting from BASH version 3.2), try this:

    if [[ ! "$1" =~ (one|two|three) ]] ; then
        echo -e "\n***Invalid number"
        usage
        exit 1
    else
        action="$1"
    fi 
    

    To be able to use quoted regex you can use:

    shopt -s compat31
    

    EDIT: As glen commented below you can use !~ operator also i.e.

    [[ "$1" !~ (one|two|three) ]]