%getname "Yao Nan" Lien
You have entered: Yao Nan Lien
=== Passing $* ===
First Name: Yao
Last Name: Nan
=== Passing $@ ===
First Name: Yao
Last Name: Nan
=== Passing "$*" ===
First Name: Yao Nan Lien
Last Name:
=== Passing "$@" ===
First Name: Yao Nan
Last Name: Lien
Tue Nov 25 23:14:36 CST 2025
Untitled Document
特殊符號 (Special Characters)
除了文字型態的關鍵詞之外,Shell 還定義了一些特殊符號,
SP
Tab
NL
=
;
&
)
(
>
<
|
^
{
}
$
;
#
*
?
[
]
`
\
'
"
Tue Nov 25 23:14:37 CST 2025
Untitled Document
特殊符號的Escape (Remove Meaning of Special Characters)
# -------------------------------------
# single quote vs double quote
# -------------------------------------
name=Clinton
echo 'My name is '$name' and today is '`date`
# -------------------------------------
echo "My name is $name and today is `date`"
#----------------------
# 印出目錄下所有檔案
#----------------------
for i in `ls`
do
echo "==== File Name: $i ===="
cat $i
done
Tue Nov 25 23:14:37 CST 2025
Untitled Document
Examples of Using Read
利用 'read' 從 /etc/passwd 檔案中抽取資訊
while IFS=: read user password uid realname homedir shell
do
echo user $user is $realname who prefers $shell
done < /etc/passwd
cat /etc/passwd |
while IFS=: read user password uid realname homedir shell
do
echo user $user is $realname who prefers $shell
done
Tue Nov 25 23:14:38 CST 2025
Untitled Document
Examples of Using Read
複製整個目錄架構,但不複製其中的檔案
1. DOS 中利用 xcopy /t 指令
2. 利用下面兩個 shell script
Script cpdir_v1
find /a/b -type d |\ #find all directories under /a/b
sed 's;/a/b/;/home/b/;' |\ #change to destination path name
sed 's/^/mkdir /' |\ #insert mkdir command
sh -x #nvoke sh to execute
Script cpdir_v2
find /a/b -type d |\ #find all directories under /a/b
sed 's;/a/b/;/home/b/;' |\ #change to destination path name
while read newdir #read new directory name
do
mkdir $newdir #make new directory
done
Tue Nov 25 23:14:38 CST 2025
Untitled Document
Nested if Structure
if
write stu1 < message
then
:
else
if mail stu1 < message
then
echo "mail sent instead"
else
echo "Could not sent instead"
fi
fi
Tue Nov 25 23:14:38 CST 2025
Untitled Document
More Codes
for person in stu1 stu2 stu3
do
if
who | grep $person > /dev/null
then
write $person < message
else
mail $person < message
fi
done
&& 或 || 也可以用在
測試條件式中連同作為 AND 及 OR ,連同 NOT 作為
邏輯運算的運算子 (logical operator)。
NOT
if ! grep QQ fileX > dev/null
then
echo QQ not found in fileX
fi
=
if grep QQ fileX > /dev/null
then
: # do nothing
else
echo QQ not found in fileX
fi
AND
if grep pattern1 myfile && grep pattern2 myfile
then
echo myfile contains both patterns
fi
OR
if grep pattern1 myfile || grep pattern2 myfile
then
echo Neither pattern1 nor pattern2 found in myfile
fi
Tue Nov 25 23:14:39 CST 2025
Untitled Document
File Testing Statement
測試檔案性質 (Test File Status)
test -r filename
Exists and readable
test -w filename
Exists and writable
test -x filename
Exists and executable
test -f filename
Exists and regular
test -d filename
Exists and directory
test -s filename
Exists and nonzero size
我們用各種格式來撰寫一個複合的條件式程式碼,讀者可以
觀摩各種增加程式可讀性的技巧。
for file
do
if test -f $file
then
if test -r $file
then
if test -x $file
then
echo "File $file is
readable and executable"
fi
fi
fi
done
for file
do
if [ -f $file ]
then
if [ -r $file ]
then
if [ -x $file ]
then
echo "File $file is
readable and executable"
fi
fi
fi
done
for file
do
if [ -f $file -a -r $file -a -x $file ]
then
echo File $file is readable and executable
fi
done
for file
do
[ -f $file -a -r $file -a -x $file ] && echo File $file is readable and executable
done
Tue Nov 25 23:14:39 CST 2025
Untitled Document
String Comparison
test "s1" = "s2"
Strings equal
test "s1" != "s2"
Strings not equal
test -z "s1"
Length of string zero
test -n "s1"
Length of string nonzero
test "s1"
Length of string nonzero
"test" 所需的參數之間以空白隔開。
注意用雙引號(" ")保護參數,防止空字串破壞程式結構。
例 Script 1
例 Script 2
noset=""
test -z $noset
test "$noset" = a
q=`who -T | grep "^s8500" | cut -c10`
if test "$q" = "+"
then
write s8500 < note
else
mail s8500 < note
fi
Tue Nov 25 23:14:39 CST 2025
Untitled Document
Numerical Comparison
test "$n1" -eq "$n2"
Equal
test "$n1" -ne "$n2"
Not equal
test "$n1" -gt "$n2"
Greater than
test "$n1" -ge "$n2"
Greater than or equal to
test "$n1" -lt "$n2"
Less than
test "$n1" -le "$n2"
Less than or equal to
例
# -----------------------------------------------
# countuser: count number of users on the system
# -----------------------------------------------
count=`who | wc -i`
if [ "$count" -le "20" ]
then
echo "$count" users - light load
else
echo "$count" users - heavy load
fi
Tue Nov 25 23:14:39 CST 2025
Untitled Document
While and Until
Syntax
while
command_lines
do
command_lines
done
until
command_lines
do
command_lines
done
'while' will test the condition to do the first iteration
'until' will do the first iteration before test the condition
Begin
while marks loop start
Control
Evaluate return code from last command before do
Middle
execute all commands within body
End
done marks loop end, shell reads until end is found
例 Script: Appends stdin to file outfile
echo "
Enter lines of input (end with ^D):
"
while read x
do
echo $x
done >> outfile
file=
verbose=
quiet=
long=
while [ $# -gt 0 ] #Loop until no args left
do
case $1 in #Check first arg
-f) file=$2
shift #Shift off "-f" so that shift at end gets value in $2
;;
-v) verbose=true; quiet= ;;
-q) quiet=true; verbose= ;;
-l) long=true ;;
--) shift #By convention, - - ends options
break
;;
-*) echo $0: $1: unrecognized option >&2 ;;
*) break ;; # Nonoption argument, break while loop
esac
shift #Set up for next iteration
done
#edit a batch of HTML files using loop and editing script
for i in *.htm
do
ex $i < ex.script
done
注意,可視性編輯器例如'vi'並不適用此法,因為
vi 必須依賴螢幕的游標才能正確的編輯。
儲存編輯指令及主程式於單一檔案
上面的方法需要用到兩個檔案,有時並不利於管理,
下面的 script 將兩個檔案整合成一個檔案:
echo '1,$s/TSMC/tsmc/g
w' > ex.script
for i in *.htm
do
ex $i < ex.script
done
利用Here儲存編輯指令及主程式於單一檔案
for i in *.htm
do
ex $i<<%
1,\$s/TSMC/tsmc/g
w
%
done
Tue Nov 25 23:14:42 CST 2025
Untitled Document
STDIN 轉向 及 Here
Here 之例
# -----------------------------------------------
# Send emails to top 10 disk space usage users
# -----------------------------------------------
cd /home #Move to top of home directories
du -s * | #Generate raw disk usage
sort -nr | #Sort numerically, highest numbers first
sed 10q | #Stop after first 10 lines
while read amount name
do
mail -s "disk usage warning" $name << EOF
Greetings. You are one of the top 10 consumers of disk space
on the system. Your home directory uses $amount disk blocks.
Please clean up unneeded files, as soon as possible.
Thanks,
Your friendly neighborhood system administrator.
EOF
done
Tue Nov 25 23:14:42 CST 2025
Untitled Document
Open a file for both input and output
program <> file
To open file for both reading and writing.
It is up to program to be aware of this and take advantage of it
not practically useful
An undocumented feature in V7 Bourne shell
Standardized in the 1992 POSIX standard,
on many systems /bin/sh doesn't support it.
Tue Nov 25 23:14:42 CST 2025
Untitled Document
Signal and Trap
Unix 信號 (Signal)
傳統電腦架構的核心是CPU,當一個程序(Process)在佔用
CPU 執行時,不會主動停下,在多工的作業系統下,作業系統可以
送信號 (Signal)給一個程序中斷之。例如 Unix 系統下,使用者
按下'^C'試圖中斷一個script 的執行程序,作業系統就會送一個
信號給該程序中斷之。
常用的 Unix Signal
Signal
Name
說明
0
EXIT
中止程序
Exit from the shell.
1
HUP
STDOUT被停止,程序要中止
A pseudosignal used by the shell, indicating
that the standard output
has hung up; sending this signal logs you out.
2
INT
鍵盤上的<Del>中止鍵被按下,程序要中止
Sent by a <Del> keystroke; sends an interrupt to
the current program.
3
QUIT
鍵盤上的 '^C'中止鍵被按下,程序要中止,core dump
Sent by a <Ctrl>\ keystroke; causes the current
program to abort,
leaving behind a core dump (for use in program debugging).
9
KILL
強迫中止程序,trap 失效
Cannot be trapped or ignored; forces the
receiving program to die.
11
SEGV
記憶體衝突,立刻中止程序,trap 失效
Indicates that a segmentation violation (a
memory fault within the
UNIX system) has occurred. This signal cannot be trapped or
ignored by a
shell; it invariably terminates the receiving process and causes
a core dump.
15
TERM
中止程序
Terminates the receiving program. (This signal
should be used in
preference to Signal 9, because the receiving program can catch
it and carry
out some shutdown operation, for example closing open files;
Signal 9 forces
the process to die immediately.)