Reputation: 390
I asked a question yesterday about trying to make sure that a date is formatted correctly. This is slightly more targeted as I've tried to write the test myself and it's not acting as I would have expected it to. (I'm new to linux, so this happens a fair amount)
I need the date inputted as YYYYMMDD. I think that the start of the if statement should be checking basically [[ check if $tDate is a zero string or if the date is not YYYYMMDD ]].
When I run the code the date is there $lastCOB (yesterday, last close of business), but when I input any date (or don't change the date), I get the "Invalid date. Please enter the correct format
." response, meaning that obviously the test doesn't believe the format to be correct, though it's entered as YYYYMMDD as i want it to be.
tDate=$(lastCOB)
tDateOkay=0
until [[ $tDateOkay -eq 1 ]] ; do
echo "$tDate"
echo "$tDateOkay"
read -p "Please Enter date for search. Use format: Date (YYYYMMDD): " -e -i "$tDate" tDate
if [[ -z "$tDate" || "$(date --date=$tDate + '%Y%m%d' 2>&1 )" != $tDate ]] ; then
echo "Invalid date. Please enter date in the correct format."
elif [[ $tDate -gt $(today) || $tDate -eq $(today) ]] ; then
echo "Date must be in the past. Please try again."
else
tDateOkay=1
fi
done
The first if statement should test for format. the elif statement should test for making sure that the date is in the past, and not future, or even today. If it passes both tests, then tDateOkay should turn to 1 from zero and the program should move on with that date as the input for the future data search. Let me know if I need to add anything for clarity.
Upvotes: 2
Views: 2952
Reputation: 289725
I think you have a problem in this line:
if [[ -z "$tDate" || "$(date --date=$tDate + '%Y%m%d' 2>&1 )" != $tDate ]] ; then
It works to me with
if [[ -z "$tDate" || "$(date --date=$tDate '+%Y%m%d' 2>&1 )" != $tDate ]] ; then
That is, put the +
inside the date format.
For the future, I recommend you to use 2>&1
when you are sure the code is fine. Otherwise it is more complicated to debug.
By the way, as stated by an answer that was deleted, the if [[ || ]]
is not the best POSIX way. In this comment I was recommended to use if [ ] || [ ]
.
Upvotes: 5