单分支的一般形式
if test 判断shell语句
then
shell语句
fi
例如:
#!/bin/bash
if test -e zc.c
then
echo "hello world"
fi
或者
#!/bin/bash
if [ -e zc.c ]
then
echo "hello world"
fi
双分支的一般形式
if test 判断shell语句
then
• shell语句1
else
shell语句2
fi
例如:
#!/bin/bash
if [ -e zc.c ]
then
echo "hello world"
else
echo "zhangcheng"
fi
多分支的一般形式
if test 判断shell语句
then
shell语句1
elif 判断语句2
then
shell语句2
else
shell语句3
fi
例如:
#!/bin/bash
if [ -e 1.c ]
then
echo "hello world"
elif [ -f 1.c ]
then
echo "day3"
else
echo "zhangcheng"
fi
练习
输入一个文件名,判断这个文件是否存在,如果存在,判断是否有可写权限,如果有,把“helloworld”写到文件里面,如果没有权限,增加可写权限,再把helloworld写进去,如果不存在,创建文件,把helloworld写进去
#!/bin/bash
read -p "please input a filename" filename
if test -e $filename
then
if test -w $filename
then
echo "hello world" >>$filename
else
chmod +w $filename
echo "hello world" >>$filename
fi
else
touch $filename
echo "hello world" >>$filename
fi