David W.
David W.

Reputation: 107080

BASH: Pattern match not working

I am using BASH 3.2. I can execute the following from the command line:

$ build_number=23332
$ if [[ $build_number != +([0-9]) ]]
> then
> echo "Bad Build Number ($build_number). No CPU time for you!"
> else
> echo "Build Number ($build_number) is numeric"
> fi
Build Number (2332) is numeric"

If I change build_number to23332a`, this returns:

Bad Build Number (23332a). No CPU time for you!

Now, I'll try to put this into my shell script:

#! /bin/bash
...
#
# Set options
#
while getopts :hu:j:b:p: option
do
    case $option in
        p)  promotion_name="$OPTARG";;
        u)  jenkins_url="$OPTARG";;
        j)  job_name="$OPTARG";;
        b)  build_number="$OPTARG"
            if [[ $build_number != +([0-9]) ]]
            then
                error "Build Number must be numeric"
            fi
        ;;
        h)  printf "\n$USAGE\n"
            exit 0;;
        *)  error "Invalid Argument";;
    esac
done
shift $(( $OPTIND - 1 ))

When I try to execute my program, I get the following error:

$ ./promotion.sh -b 238d -jasdad
./promotion.sh: line 55: syntax error in conditional expression: unexpected token `('
./promotion.sh: line 55: syntax error near `+(['
./promotion.sh: line 55: `      if [[ $build_number != +([0-9]) ]]'

So, what am I doing wrong?

Upvotes: 0

Views: 298

Answers (2)

Pablo208
Pablo208

Reputation: 23

well the most obvious thing is that the plus checks if the pre-ceeding character matches the pattern , here you have no pre-ceeding character put the plus after it

Upvotes: 0

choroba
choroba

Reputation: 242103

You need to enable extended globbing:

shopt -s extglob

Upvotes: 2

Related Questions