条件测试:test [
-测试一个条件是否成立,
- 如果结果为真,则结果=0
- 如果结果为假,则结果=1
python@ubuntu:~/1004$ var=2
python@ubuntu:~/1004$ test $var
python@ubuntu:~/1004$ echo $?
0
python@ubuntu:~/1004$ test $var -gt 5
python@ubuntu:~/1004$ echo $?
1
或者:
(注意: 两边加空格)
python@ubuntu:~/1004$ [ $var -gt 1 ]
python@ubuntu:~/1004$ echo $?
0
语法错误:
python@ubuntu:~/1004$ [ $s1 = $s4 ]
bash: [: hello: 需要一元表达式
需要加"" : [ "$s1" = "$s4" ]
if/then/elif/else/fi
实现分支控制
- 判断是否事目录-d (-f文件)
- fi:判断if结束的关闭标签
#! /bin/sh
if [ -d ~/Desktop ]; then
echo "Desktop is dir"
echo "dimples"
fi
source t2.sh
- :空命令(不做任何事,执行总是真)
- read命令:等待用户输入一行字符串,存到shell变量中
#! /bin/sh
echo "it is morniing? yes or no"
read YES_OR_NO
if [ "$YES_OR_NO" = "yes" ]; then
echo "早上好"
elif [ "$YES_OR_NO" = "no" ]; then
echo "中午好"
else
echo "sorry"
exit 1
fi
exit 0
python@ubuntu:~/1004$ vi t3.sh
python@ubuntu:~/1004$ chmod a+x t3.sh
python@ubuntu:~/1004$ ./t3.sh
it is morniing? yes or no
yes
早上好
case/esac
- 类似C语言的switch/case语句
- esac表示case语句块的结束
#! /bin/sh
echo "is it morning"
read YES_OR_NO
case "$YES_OR_NO" in
yes|y|Yes|YES)
echo "早上好";;
[nN]*)
echo "中午好";;
*)
echo "sorry"
exit 1;;
esac
exit 0
- source执行结果会传递给shell,shell退出了
- 必须用chmod:
python@ubuntu:~/1004$ chmod a+x t4.sh
python@ubuntu:~/1004$ ./t4.sh
case语句的例子可以在系统服务的脚本目录 /etc/init.d中找到。这个目录下都是启动脚本程序。
循环语句
for/do/done
- 类似于foreach循环
- 反引号:``执行命令
#! /bin/sh
for FRUIT in apple pear banana; do
echo "I like $FRUIT"
done
python@ubuntu:~/1004$ source t5.sh
I like apple
I like pear
I like banana
while/do/done
#! /bin/sh
echo "输入密码:"
read PWD
while [ "$PWD" != "111111" ]; do
echo "Sorry, try again"
read PWD
done
python@ubuntu:~/1004$ source t6.sh
输入密码:
1
Sorry, try again
2
Sorry, try again
111111
通过算数运算控制循环的次数:
- 用户最多可已输入5次密码,输入正确直接结束
#! /bin/sh
echo "请输入密码"
read PWD
COUNTER=1
while [ "$COUNTER" -lt 6 ]; do
if [ "$PWD" != "123" ]; then
#break
if [ "$COUNTER" -eq 5 ]; then
echo "输入错误,没有机会啦"
else
echo = "输入错误,再来一次"
read PWD
fi
else
echo "输入成功"
break
fi
COUNTER=$(($COUNTER+1))
done