只要講到『程式』的話,那麼條件判斷式,亦即是『 if then 』這種判別式肯定一定要學習的!因為很多時候,我們都必須要依據某些資料來判斷程式該如何進行。
這個 if .... then 是最常見的條件判斷式了~簡單的說,就是當符合某個條件判斷的時候,就予以進行某項工作就是了。這個 if ... then 的判斷還有多層次的情況!我們分別介紹如下:
如果你只有乙個判斷式要進行,那麼我們可以簡單的這樣看:
if [ 條件判斷式 ]; then
當條件判斷式成立時,可以進行的命令工作內容;
fi <==將 if 反過來寫,就成為 fi 啦!結束 if 之意!
例子:
[root@www scripts]# cp sh06.shsh06-2.sh <==用改的比較快!
[root@www scripts]# vi sh06-2.sh
#!/bin/bash
# program:
# this program shows the user's choice
# history:
# 2005/08/25 vbird first release
path=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export path
read -p "please input (y/n): " yn
if [ "$yn" == "y" ] ||[ "$yn" == "y" ]; then
echo "ok, continue"
exit 0
fiif [ "$yn" == "n" ] ||[ "$yn" == "n" ]; then
echo "oh, interrupt!"
exit 0
fiecho "i don't know what your choiceis" && exit 0
簡單語法
# 乙個條件判斷,分成功進行與失敗進行(else)
if [ 條件判斷式 ]; then
當條件判斷式成立時,可以進行的命令工作內容;
else
當條件判斷式不成立時,可以進行的命令工作內容;
fi更複雜的情況,則可以使用這個語法:
# 多個條件判斷 (if ... elif... elif ... else) 分多種不同情況執行
if [ 條件判斷式一 ]; then
當條件判斷式一成立時,可以進行的命令工作內容;
elif [ 條件判斷式二 ]; then
當條件判斷式二成立時,可以進行的命令工作內容;
else
當條件判斷式一與二均不成立時,可以進行的命令工作內容;
fi例子
[root@www scripts]# cp sh06-2.sh sh06-3.sh
[root@www scripts]# vi sh06-3.sh
#!/bin/bash
# program:
# this program shows the user's choice
# history:
# 2005/08/25 vbird first release
path=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export path
read -p "please input (y/n): " yn
if [ "$yn" == "y" ] ||[ "$yn" == "y" ]; then
echo "ok, continue"
elif [ "$yn" == "n" ]|| [ "$yn" == "n" ]; then
echo "oh, interrupt!"
else
echo "i don't know what your choice is"
fi
他的語法如下:
case $變數名稱 in <==關鍵字為 case ,還有變數前有錢字型大小
"第乙個變數內容") <==每個變數內容建議用雙引號括起來,關鍵字則為小括號 )
程式段;; <==每個類別結尾使用兩個連續的分號來處理!
"第二個變數內容")
程式段*) <==最後乙個變數內容都會用 *來代表所有其他值
不包含第乙個變數內容與第二個變數內容的其他程式執行段
exit 1
esac <==最終的 case 結尾!『反過來寫』思考一下!
例子[root@www scripts]# vi sh09-2.sh
#!/bin/bash
# program:
# show "hello" from $1.... by using case .... esac
# history:
# 2005/08/29 vbird first release
path=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export path
case $1 in
"hello")
echo "hello, how are you ?"
echo "you must input parameters, ex> "
*) # 其實就相當於萬用位元組,0~無窮多個任意位元組之意!
echo "usage $0 "
esac
shell 條件判斷式語句
shell兩種判斷格式 test e root install.log e root install.log 最常用 d root echo yes echo no 第乙個判斷命令如果正確執行,則列印 yes 否則列印 no 建立個硬鏈結吧 root student.txt ef tmp stu.t...
Shell學習筆記 條件判斷式
1.判斷格式 1 test 引數 檔案 例 test e root install.log 2 引數 檔案 推薦使用 例 e root install.log 注意 中括號後面和前面需要有空格 2.判斷檔案型別引數 1 d 檔案 判斷該檔案是否存在,並且是否為目錄檔案 2 e 檔案 判斷檔案是否存在...
Shell條件判斷
b file 若檔案存在且是乙個塊特殊檔案,則為真 c file 若檔案存在且是乙個字元特殊檔案,則為真 d file 若檔案存在且是乙個目錄,則為真 e file 若檔案存在,則為真 f file 若檔案存在且是乙個規則檔案,則為真 g file 若檔案存在且設定了sgid位的值,則為真 h fi...