if construction:
if...else...fi
Syntax:
if condition
then
#condition为真,执行所有块内的commands直到else
else
#condition为假,执行所有的块内的commands直到fi
fi
e.g.1:
#!/bin/bash
#
#检验输入的数是正数还是负数
#
#[]两头一定要有空格!!!
if [ $# -eq 0 ]
then
echo "$0 : you must give one integers!"
exit 1
fi
if test $1 -ge 0
then
echo "$1 number is positive"
else
echo "$1 number is negative"
fi
[fedora@novice shell_scripts]$ sh isnump_u
isnump_u : you must give one integers!
[fedora@novice shell_scripts]$ sh isnump_u 7
7 number is positive
[fedora@novice shell_scripts]$ sh isnump_u -9
-9 number is negative
嵌套if:
Syntax:
if condition
then
if condition
then
.....
..
do this
else
....
..
do this
fi
else
...
.....
do this
fi
e.g. 2:
#!/bin/bash
#
#nested if
#
osch=0
echo "1. unix (sun os)"
echo "2. linux (fedora)"
read osch
if [$osch -eq 1 ];then
echo "You pick up unix (sun os)"
else
if [ $osch -eq 2 ]
then
echo "You pick up linux (fedora)"
else
echo "what you do not like unix/linux os"
fi
fi
多级if:
Syntax:
if condition
then
.......
elif condition1
then
.........
elif condition2
then
...........
else
..........
fi
e.g. 3:
#!/bin/bash
#
if [ $# -eq 0 ];then
echo "Please enter some arguments"
elif [ $1 -gt 0 ];then
echo "$1 is positive"
elif [ $1 -lt 0 ];then
echo "$1 is negative"
elif [ $1 -eq 0 ];then
echo "$1 is zero"
else
echo "Opps! $1 is not number,give number"
fi
e.g. 4:
#!/bin/bash
#
if [ $# -eq 0 ];then
echo "Please enter some arguments"
else
if [ $1 -gt 0 ];then
echo "$1 is positive"
elif [ $1 -lt 0 ];then
echo "$1 is negative"
elif [ $1 -eq 0 ];then
echo "$1 is zero"
else
echo "Opps! $1 is not number,give number"
fi
fi
****************
*如果then与if在一行,则在在条件判断后加一个分号,如果then另起一行则不要加分号
*if中的条件判断可以是 [],或test;如果是[]的话,左括号的右端及右括号的左端必须有空格
*各种if可以相互嵌套
阅读(886) | 评论(0) | 转发(0) |