<4>. 控制结构
4.1 条件判定
在shell中条件判断是通过test命令或者是[ ]实现, 判断条件如下:
数学运算:
a -eq b :a == b
a -ne b : a != b
a -lt b : a < b
a -le b : a <= b
a -gt b : a > b
a -ge b : a >= b
string比较:
string1 = string2
string1 != string2
string1 : string1 不是NULL,或者是没有定义
4.2 组合判定
逻辑运算符:
! : not
exp1 -a exp2 : a && b
exp1 -o exp2 : exp1 || exp2
4.3 if-else结构:
!/bin/sh#
# see whether arguments is positive
#
if [ $# -ne 1 ]
then
echo"$0 : you must give/supply one integers"
exit1
fi
if test $1 -gt 0
then
echo"$1 number is postivie"
else
echo"$1 number is negative"
fi
# see whether arguments is positive
#
if [ $# -ne 1 ]
then
echo"$0 : you must give/supply one integers"
exit1
fi
if test $1 -gt 0
then
echo"$1 number is postivie"
else
echo"$1 number is negative"
fi
#!/bin/sh
osch=0
echo"1. unix(sun os)"
echo"2. linux(Red Hat)"
echo -n "select your os choice [1 or 2] ?"
read osch
if [ $osch -eq 1 ]
then
echo"you pick up unix"
else
#
# nested if
if [ $osch -eq 2 ]
then
echo"you pick up linux"
else
echo"what you donot like unix/linux"
fi
fi
osch=0
echo"1. unix(sun os)"
echo"2. linux(Red Hat)"
echo -n "select your os choice [1 or 2] ?"
read osch
if [ $osch -eq 1 ]
then
echo"you pick up unix"
else
#
# nested if
if [ $osch -eq 2 ]
then
echo"you pick up linux"
else
echo"what you donot like unix/linux"
fi
fi
#!/bin/sh
#
# test the if.. elif ..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"$1 is not a number"
fi
#
# test the if.. elif ..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"$1 is not a number"
fi
4.4 for
!/bin/sh
## test for
#
for i in 12345
do
echo"welcome $i times"
done
#!/bin/bash
for(( i =0; i <=5; i++))
do
echo"welcome $i times"
for(( i =0; i <=5; i++))
do
echo"welcome $i times"
done
Tip 1. 注意程序中使用的shell脚本的类型
#!/bin/bash
for(( i =1; i <=5; i++))
do
for(( j =1; j <=5;++j ))
do
echo -n "$i"
done
#print a new line
echo""
done
for(( i =1; i <=5; i++))
do
for(( j =1; j <=5;++j ))
do
echo -n "$i"
done
#print a new line
echo""
done
