Atomiklan
Atomiklan

Reputation: 5434

Bash conditional regex

Any idea what I did wrong in this conditional regex?

MIN="30"

if ! [[ "$MIN" =~ [0-5]?[0-9]|\* ]]; then
  echo "INVALID MINUTE"
else
  echo "VALID MINUTE"
fi

Thanks

* UPDATE *

You didn't include the wildcard match. I need to do this using pure regex as I have other conditions that need to be met as well such as hour, month (more complex), and day of week like so:

[1-2]?[0-9]|\* - This is for hour
[1-3]?[0-9]|\* - This is for day of month
1?[0-9]|\*     - This is for month of year 
[0-7]|\*       - This is for day of week (0 = sunday etc)

ie minutes must be number for first and second place holders or can be a wildcard to match every possible minute 0 - 59

In fact now that I look at it, this solution will not work for day of month as someone could enter 39 which is not a valid day of the month.

* UPDATE *

Well I didn't completely follow your logic at first, but I think you're on to something. This may actually work and will be simpler. I like over complicating things...

if ! [[ "$MIN" -gt 0 && "$MIN" -lt 59 || "$MIN" == "\*" ]]; then

I'm just having trouble now with it literally evaluating (well comparing) the wildcard.

Any thoughts here. Googling in the mean time.

* UPDATE *

if [ "$MIN" -gt 0 ] && [ "$MIN" -lt 59 ] || [ "$MIN" = "*" ]; then

Just tested it again and checked my syntax. When MIN is between 0 and 59 it works great (true), when MIN is over 59 it also works (reports false), however as soon as you try to set MIN to an * the IF statement freaks and pops out:

line 340: [: *: integer expression expected

Upvotes: 0

Views: 924

Answers (2)

John_West
John_West

Reputation: 2399

Your problem was (as explained in UPD) you had not been able to compare variable both with string and with integer in one conditional string.

I suggest you to compare vs string (* symbol) at first, then eval and compare to integer

MIN="*"; #try also other MIN values

k=0; # flag. 1 - if valid, 0 - if invalid

if [ "$MIN" == "*" ]; then
    k=1;
else
    eval "MIN=$MIN";
    if [ "$MIN" -gt 0 ] && [ "$MIN" -lt 59 ]; then
        k=1;
    fi;
fi;

if [ $k -eq 0 ]
    echo "INVALID MINUTE"
else
    echo "VALID MINUTE"
fi

Upvotes: 0

Mehul Rathod
Mehul Rathod

Reputation: 1244

I think you are double negating your condition, also have you considered just using numeric operators?

min="30"

if ! [[ "$min" -gt 0 && "$min" -lt 59 ]]; then
  echo "INVALID MINUTE"
else
  echo "VALID MINUTE"
fi

Upvotes: 1

Related Questions