Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

my script name is 1. when i type in "1 2012 12 12". it shows current date calendar and when i enter a invaild date like "1 2323232" cal gives me a error so how could i put that in if loop that if it gives error it echos "date is not valid"

year=$(echo "$year" | bc)
month=$(echo "$month" | bc)
day=$(echo "$day" | bc)

cal $day $month $year

if [ $? -eq 0];
        then
        echo "Date is valid"
else
        echo "Date in not valid"
fi
share|improve this question
1  
What, exactly, is your question? You ask, "how to write this if command?", but you seem to have written it. Is it not working? And BTW, what would you want the loop do to? Process the same input repeatedly? That will just produce the error message an infinite number of times. ... ... ... (P.S. Your script name is "1"? Ugh.) –  G-Man Oct 7 '14 at 23:22
1  
Is this some massive school project about calendar usage? We've just seen almost the same piece of code here: unix.stackexchange.com/questions/159888/… –  jimmij Oct 7 '14 at 23:32

1 Answer 1

This won't work:

cal $day $month $year

cal expects only month and year arguments. Try:

cal $month $year

If you want to print a message if the month and year are invalid, there is no need for a loop. The following code will display a calendar if the month and year are valid or an error message if they are not:

cal $day $month $year 2>/dev/null || echo "Date is not valid."

The statement following || is only executed if the statement preceding it finishes with a non-zero return code (indicating that an error occurred).

Aside

These lines do not appear to accomplish much:

year=$(echo "$year" | bc)
month=$(echo "$month" | bc)
day=$(echo "$day" | bc)

If the variables year, month, and day, are valid, these lines do nothing. If they are not valid numbers, bc will spit out an uncaught error.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.