1. Home
  2. Computing & Technology
  3. Linux

Bash Guide For Beginners

From

7.2.3. Nested if statements

Inside the if statement, you can use another if statement. You may use as many levels of nested if s as you can logically manage.

This is an example testing leap years:


   

anny ~/testdir> cat testleap.sh
#!/bin/bash
# This script will test if we're in a leap year or not.

year='date +%Y'

if [ $[$year % 400] -eq "0" ]; then
echo "This is a leap year. February has 29 days."
elif [ $[$year % 4] -eq 0 ]; then
if [ $[$year % 100] -ne 0 ]; then
echo "This is a leap year, February has 29 days."
else
echo "This is not a leap year. February has 28 days."
fi
else
echo "This is not a leap year. February has 28 days."
fi

anny ~/testdir> date
Tue Jan 14 20:37:55 CET 2003

anny ~/testdir> testleap.sh
This is not a leap year.

* License

* Bash Guide For Beginners Index

Explore Linux
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Linux
  4. Linux Documentation
  5. Bash Guide for Beginners
  6. Bash Guide For Beginners - 7.2.3. Nested if statements

©2009 About.com, a part of The New York Times Company.

All rights reserved.