一、if语句
1、简单的if语句
#!/bin/bash
if [ $# = 0 ];then # [ ] 括号中必须使用空格,$#参数个数
echo "no parameter."
exit 1
fi
echo $#
exit
执行脚本结果:
# ./test.sh
no parameter.
# ./test.sh abc
1
2、if else 语句
#!/bin/bash
if [ $1 -lt 0 ];then # $1第一个参数
echo Negative Number.
else
echo Nonnegative Number.
fi
exit
执行脚本结果:
# ./test.sh 1
Nonnegative Number.
# ./test.sh -1
Negative Number.
二、case语句
case 变量 in
模式1)
语句块1
;;
模式2)
语句块2
;;
........
esac
#!/bin/bash
while true #死循环等待输入
do
echo "please enter yes or no?"
read RST
case "$RST" in
y|yes) # 输入 y 或 yes
echo "you enter yes."
break #跳出while
;;
n|no)
echo "you enter no."
break
;;
*)
echo "you enter error."
;;
esac
done
脚本执行结果:
# ./test.sh
please enter yes or no?
r
you enter error.
please enter yes or no?
y
you enter yes.
# ./test.sh
please enter yes or no?
n
you enter no.
三、for语句
for 变量 in 列表
do
语句块
done
#!/bin/bash
i=0
for i in 1 2 3 4 5 6 7 8 9
do
if [ $i = 5 ];then
continue
fi
echo "LOOP="$i
done
执行结果:
# ./test.sh
LOOP=1
LOOP=2
LOOP=3
LOOP=4
LOOP=6
LOOP=7
LOOP=8
LOOP=9
#!/bin/bash
for loop in $* # $*参数列表
do
echo $loop
done
执行结果:
# ./test.sh a b c d
a
b
c
d
四、while语句
while 条件测试
do
语句块
done
#!/bin/bash
i=0
while [ $i -lt 5 ]
do
if [ $i = 4 ];then
break #跳出循环
fi
echo "loop:"$i
((i++))
done
执行结果:
# ./test.sh
loop:0
loop:1
loop:2
loop:3
#具体的测试条件,可以man test查看