0

I have one shell script which is taking date as input in YYYYMMDD format. I need to put a validation for the user input, so that it should accept only greater than one week's after date (eg. if today is 20140703, then it should accept 20140710 or greater than that), and no string, only 8 digit numeric value.

My existing code to read the date and capturing next one week date is

echo "Please enter a date in YYYYMMDD format" read my_date next_week_date=$(date --date "+1 week" +%Y%m%d) 

How i should procceed with the validation.

0

2 Answers 2

1

You can validate your date like this

# [[:digit:]] - indicate the digits only # {NUM} - Indicate the number of occurrences # ^ - From Starting # $ - To Ending if [[ $my_date =~ ^[[:digit:]]{8}$ ]] && [[ $my_date -ge $next_week_date ]] then echo "valid" else echo "Not valid" fi 
Sign up to request clarification or add additional context in comments.

Comments

0

To check if the input contains 8 digits, you can use the following code, where fail can be as simple as exit 1:

echo $my_date | grep "^[0-9]\{8\}$" > /dev/null || fail() 

For the date validation, you can use this:

[ $(date -d $my_date +%s) -lt $(date --date "+1 week" +%s) ] && fail() 

The +%s format converts the date to timestamp, which is the unix time (number of seconds since 01/01/1970).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.