0

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
  • 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 Says 'Reinstate Monica' Oct 07 '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: http://unix.stackexchange.com/questions/159888/just-wanted-to-know-what-am-i-doing-wrong-in-the-end-of-this-script-that-doesnt – jimmij Oct 07 '14 at 23:32

1 Answers1

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.

John1024
  • 74,655