一 语法
if [ 条件判断式 ]
then
当条件判断式1成立时,执行程序1
elif[ 条件判断式2 ]
then
当条件判断式2成立时,执行程序2
省略更多条件
else
当所有条件都不成立时,最后执行程序
fi
二 实现计算器
#!/bin/bash
read -t 30 -p "please input num1:" num1
read -t 30 -p "please input num2:" num2
read -t 30 -p "please input a operator:" ope
if [ -n "$num1" -a -n "$num2" -a -n "$ope" ]
then
test1=$(echo $num1|sed 's/[0-9]//g')
test2=$(echo $num2|sed 's/[0-9]//g')
if [ -z "$test1" -a -z "$test2" ]
then
if [ "$ope" == "+" ]
then
sum=$(($num1 + $num2))
elif [ "$ope" == "-" ]
then
sum=$(($num1 - $num2))
elif [ "$ope" == "*" ]
then
sum=$(($num1 * $num2))
elif [ "$ope" == "/" ]
then
sum=$(($num1 / $num2))
else
echo "Please enter a valid symbol"
exit 10
fi
else
echo "please input a num"
exit 11
fi
else
echo "please input a content:"
exit 12
fi
echo "$num1 $ope $num2 : $sum"
三 测试
please input num1:re
please input num2:23
please input a operator:1
please input a num
[root@localhost shell]# echo $?
11
[root@localhost shell]# ./shell5.sh
please input num1:
please input num2:
please input a operator:
please input a content:
[root@localhost shell]# echo $?
12
[root@localhost shell]# ./shell5.sh
please input num1:12
please input num2:23
please input a operator:gf
Please enter a valid symbol
[root@localhost shell]# echo $?
10
[root@localhost shell]# ./shell5.sh
please input num1:32
please input num2:12
please input a operator:-
32 - 12 : 20
[root@localhost shell]# ./shell5.sh
please input num1:76
please input num2:45
please input a operator:*
76 * 45 : 3420
[root@localhost shell]# ./shell5.sh
please input num1:87
please input num2:56
please input a operator:/
87 / 56 : 1
[root@localhost shell]# ./shell5.sh
please input num1:45
please input num2:23
please input a operator:+
45 + 23 : 68
#!/bin/bash
read -t 30 -p "please input a file name:" file
if [ -z "$file" ]
then
echo "qing shuru neirong"
exit 11
elif [ ! -e "$file" ]
then
echo "qing shuru wenjianming"
exit 12
elif [ -f "$file" ]
then
echo "$file is a regular file"
elif [ -d "$file" ]
then
echo "$file is a mulu"
else
echo "$file is another file"
fi