0

Firstly, yes I have read this:

Bash scripting, multiple conditions in while loop

The answer is probably in that post but I'm failing to see it so I hope someone can help. I want to test for two conditions in my while loop, essentially I want to combine these two tests which are currently nested, one's just a regex, and the second is to test if it is actually a valid date:

while ! [[ "$searchDate" =~ ^[0-9]{1,2}[a-zA-Z]{3}[0-9]{4}$ ]]; do
    read -p "Enter date in format DDmmmYYYY: " searchDate

    while ! (date -d $searchDate); do
        read -p "That date doesn't appear to be valid, try again: " searchDate
    done
done

I feel like I should be able to write something like:

while [[ ! "$searchDate" =~ ^[0-9]{1,2}[a-zA-Z]{3}[0-9]{4}$ ]] || ( ! date -d $searchDate); do
    read -p "There's something funky about that date, try again: " searchDate

but I can't get it to work, I'm not sure if it's my logic that's skewiff, or the way I'm trying to combine the tests (or both!)...

3
  • ! can only use used immediately after if or while you can't put it into a subshell by itself. Commented Apr 8, 2015 at 17:32
  • 2
    @Barmar you can put ! in front of any (single or multistage) pipeline, including in front of a simple command in a subshell as shown here. It's not specific to if or while in any way. Commented Apr 8, 2015 at 17:38
  • That code in your comment doesn't assign to searchDate. Commented Apr 8, 2015 at 17:46

1 Answer 1

2

You can do

while [[ ! "$searchDate" =~ ^[0-9]{1,2}[a-zA-Z]{3}[0-9]{4}$ ]] || ! date -d $searchDate; do
    read -p "Enter date in format DDmmmYYYY: " searchDate
done
Sign up to request clarification or add additional context in comments.

2 Comments

There's no reason for the sub-shell around the date command.
Thanks, Yes very true, I had also realized that after posting but while debating another answer this change slipped my mind.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.