你或許使用過 .BAT 來當(dāng)做一長串命令的縮寫 (我常做這種事). 這件事可以藉由在
PRofile 或 .profile 中設(shè)定 alias 來達(dá)成. 但是, 一旦 .BAT 檔太過復(fù)雜, 那麼你
會喜歡由 shell 提供的敘述語言 (Scripting language) : 它幾乎和 Qbasic 一樣強(qiáng)
大而且易用. 它可以使用變數(shù), 可以擁有像是 while , for, case if.. then .. else,
的語法結(jié)構(gòu); 它還有其它的優(yōu)點 -- 例如, 它可以當(dāng)成是程式語言的替代品.
要撰寫一個 script - 就像在 DOS 下寫 .BAT 檔一樣 - 只要編寫一個 ASCII 的檔案,
內(nèi)含你想要的指令, 然後儲存, 再使用下面這個命令讓它可以被執(zhí)行:
$ chgmod u+x <scriptfile>
當(dāng)要執(zhí)行時, 只要鍵入它的檔名就可以了.
這里有個小小的警告: 系統(tǒng)內(nèi)定的編輯器叫作 vi, 它有一點難以使用, 我想你應(yīng)該也
會這樣認(rèn)為它有些煩人. 我不會在這篇文章中討論它 -- 我自己也還尚未找到使用的竅
門 :p 請參考 Matt Welsh 的 "linux installation... ", 109 頁. 但你也可以使用其
它的編輯器, 如 joe 或是 X 下的 emacs. 這里只稍為說明一點你必需知道的 vi 知識
(至少讓你可以 quit :p )
- - 加入一段文字可以用在文章中按下 'i';
- - 離開 vi 但不儲存文章 : 請按 ESC 再打 :q!
- - 離開且存存 : 按 ESC, 再打 :wq
在 Linux 中編寫 shell script 是一門大學(xué)問 -- 它幾乎要一本書才能講得具體.
本文不會再更深入的討論這個問題; 但是, 以下提供了幾個有用(希望是)的范例, 希望
能夠使你對 shell script 有個初步的了解.
EXAMPLE 1: first_script
#!/bin/sh
# I am a comment
# don't change the first line - it's got to be there
echo "Today is `date`"
echo "My name is "$0
echo "You gave me the following "$#" parameters: "$*
echo "First parameter is "$1
echo "Have you grasped the trick?"
EXAMPLE 2: 2exe
#!/bin/sh
echo "making "$1" executable... "
chmod u+x $1
EXAMPLE 3: backup
#!/bin/sh
echo "Copying files in ~/bak... "
for name in $*
do
cp ${name} ~/bak
done
EXAMPLE 4: fmta
#!/bin/sh
echo "I remind you that only root can format disks"
fdformat /dev/fd0H1440
mkfs -t ext2 -c /dev/fd0H1440
echo "disk formatted."
EXAMPLE 5: mnta
#!/bin/sh
echo "I remind you that only root can mount disks"
mount -t msdos /dev/fd0 /mnt
echo "don't forget to umount when you've done."