Basic bash shell programming question

Soldato
Joined
18 May 2010
Posts
22,937
Location
London
Trying to improve my skills and currently undertaking a bit of self taught bash programming.

I'm working on a little script that along with a few other things will calculate if the year is a leap year if the month is Feb.

I found the following script online and I'm trying to incorporate it in to my script.

However I cannot understand the values of y and year.



echo "Enter Year:" # So for example if 2016 is entered
read y This would make the value of y 2016

year=$y Here I understand it to mean the variable y = the variable year

y=$(( $y % 4 )) This is where I start getting confused. Why are we defining what the variable y equals again?

if [ $y -eq 0 ]
then
echo "$year is Leap Year!"
else
echo "$year is not a Leap Year!"
fi


I understand what the gist of it is. It basically tests to see if the year is equally divisible by 4 if it is it is leap year, if it isn't it is not a leap year.
 
Basically after the "read y" the "year=$y" line is just so that when reporting the result "$year" is equal to what you entered, after overriding y with the calculation.

It's badly written really by overwriting y, would be nicer if instead you had something like "leapyear=$(( $y % 4 ))" and then checked that against 0, preserving y to be echo'd in the result.
 
SKILL is right, that code is not great ... personally I'd probably do something like the following (not tested)

Code:
echo "Enter Year: "; read year

leap_test=$(( $year % 4 )) 

if [ $leap_test -eq 0 ]; then
  echo "$year is Leap Year!"
else
  echo "$year is not a Leap Year!"
fi
(which is basically what SKILL said). There are probably more elegant ways of doing it though.
 
Back
Top Bottom