GB | BIG5
|
| 首頁 > 編程技術 > Shell > 正文 |
 |
| Linux程式設計-11.Shell Script(bash)--(9)流程控制if |
| http://www.openchess.org/noitatsko/programming/ (2001-05-25 16:10:00) |
if list then list [ elif list then list ] ... [ else list ] fi
幾種可能的寫法
--------------------------------------------------------------------------------
第一種
if list then
do something here
fi
當list表述返回值為True(0)時,將會執行"do something here"。
例一 : 當我們要執行一個命令或程式之前,有時候需要檢查該命令是否存在,然後才執行。
if [ -x /sbin/quotaon ] ; then
echo "Turning on Quota for root filesystem"
/sbin/quotaon /
fi
例二 : 當我們將某個檔案做為設定檔時,可先檢查是否存在,然後將該檔案設定值載入。
# Filename : /etc/ppp/settings
PHONE=1-800-COLLECT
#!/bin/sh
# Filename : phonebill
if [ -f /etc/ppp/settings ] ; then
source /etc/ppp/settings
echo $PHONE
fi
執行
[foxman@foxman ppp]# ./phonebill
1-800-COLLECT
--------------------------------------------------------------------------------
第二種
if list then
do something here
else
do something else here
fi
例三 : Hostname
#!/bin/sh
if [ -f /etc/HOSTNAME ] ; then
HOSTNAME=`cat /etc/HOSTNAME`
else
HOSTNAME=localhost
fi
--------------------------------------------------------------------------------
第三種
if list then
do something here
elif list then
do another thing here
fi
例四 : 如果某個設定檔允許有好幾個位置的話,例如crontab,可利用if then elif fi來找尋。
#!/bin/sh
if [ -f /etc/crontab ] ; then
CRONTAB="/etc/crontab"
elif [ -f /var/spool/cron/crontabs/root ] ; then
CRONTAB="/var/spool/cron/crontabs/root"
elif [ -f /var/cron/tabs/root ] ; then
CRONTAB="/var/cron/tabs/root"
fi
export CRONTAB
--------------------------------------------------------------------------------
第四種
if list then
do something here
elif list then
do another thing here
else
do something else here
fi
例五 : 我們可利用uname來判斷目前系統,並分別做各系統狀況不同的事。
#!/bin/sh
SYSTEM=`uname -s`
if [ $SYSTEM = "Linux" ] ; then
echo "Linux"
elif [ $SYSTEM = "FreeBSD" ] ; then
echo "FreeBSD"
elif [ $SYSTEM = "Solaris" ] ; then
echo "Solaris"
else
echo "What?"
fi
(http://www.fanqiang.com)
進入【UNIX論壇】
|
|
| 相關文章 |
Linux程式設計-31.工作群資訊管理(grp) (2001-05-27 22:08:00) Linux程式設計-30.使用者資訊管理(pwd) (2001-05-27 21:04:00) Linux程式設計-29.時間處理 (2001-05-27 20:10:01) Linux程式設計-28.GNU Make (2001-05-27 19:00:00) Linux程式設計-27.GNU Debugger (2001-05-27 18:08:01) Linux程式設計-26.PIPE (2001-05-27 17:04:00) Linux程式設計-25.Message Queues (2001-05-27 16:10:00) Linux程式設計-24.Semaphores (2001-05-27 15:00:00) Linux程式設計-23.共享記憶體(Shared Memory) (2001-05-27 14:08:00) Linux程式設計-20.getopt (2001-05-27 13:04:00)
|
===更多相關=== |
|
|
 |
★ 樊強制作 歡迎分享 ★ |