一 語法
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
多分支語句(case)
環境配置 測試指令碼 test.sh pattern 模式 式 格局 樣式 case語法 case 1 in pattern1 語句1 pattern2 語句2 patternn 語句n 例如 root jack31 vim if.sh bin bash test case 1in monitor ...
shell流程控制之多分支case語句
1.case與if elif else 它們都是多分支條件句,不同的是,case語句只能判斷一種條件關係,而if語句可以判斷多種關係2.格式 case 變數名 in 值1 如果變數的值等於值1,則執行程式1 值2 如果變數的值等於值2,則執行程式2 如果變數的值都不是以上的值,則執行此程式 esac...
shell case語句多分支判斷
shell指令碼,case多條件判斷語法基本格式 bin bash op 1 case in 條件1 cmd 1 cmd 2 條件2 cmd 1 cmd 2 cmd 1 cmd 2 exit 1 可以加退出值 esaccase取值後面必須為關鍵字 in,每一模式必須以右括號結束。條件1 條件2 取值...