在 if 语句里面,你可以使用另外一个 if 语句。只要你能逻辑管理
你就可以使用多层嵌套。
以下是一个测试闰年的例子:
以下是一个测试闰年的例子:
#!/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
# 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
# echo `date +%Y`
2009
# ./leapyear.sh
This is not a leap year. February has 28 days.
2009
# ./leapyear.sh
This is not a leap year. February has 28 days.
--------------------------------------------------------------------
以上的脚本可以用布尔操作符 “AND(&&)” 和 “OR(||)” 来缩短
#!/bin/bash
# This script will test if we're in a leap year or not.
year=`date +%Y`
if (( ("$year" % 400) == "0" )) || ((("$year" % 4 == "0") && ("$year" % 100 != "0") )); then
echo "This is a leap year."
else
echo "This is not a leap year."
fi
#!/bin/bash
# This script will test if we're in a leap year or not.
year=`date +%Y`
if (( ("$year" % 400) == "0" )) || ((("$year" % 4 == "0") && ("$year" % 100 != "0") )); then
echo "This is a leap year."
else
echo "This is not a leap year."
fi
# ./leapyear2.sh
This is not a leap year.
This is not a leap year.
--------------------------------------------------------------------------
同样可以使用内建命令read来捕捉用户的输入,来测试是否为闰年:
#!/bin/bash
# This script will test if you have given a leap year or not.
echo "Type the year that you want to check (4 digits), followed by [ENTER]:"
read year
if (( ("$year" % 400) == "0" )) || (( ("$year" % 4 == "0") && ("$year" % 100 !=
"0") )); then
echo "$year is a leap year."
else
echo "This is not a leap year."
fi
# This script will test if you have given a leap year or not.
echo "Type the year that you want to check (4 digits), followed by [ENTER]:"
read year
if (( ("$year" % 400) == "0" )) || (( ("$year" % 4 == "0") && ("$year" % 100 !=
"0") )); then
echo "$year is a leap year."
else
echo "This is not a leap year."
fi
# ./leap2.sh
Type the year that you want to check (4 digits), followed by [ENTER]:
2009
This is not a leap year.
Type the year that you want to check (4 digits), followed by [ENTER]:
2009
This is not a leap year.
转载于:https://blog.51cto.com/tech110/235167