Scripts
/)
Cyril Huang
[email protected]
uÌã
June 14, 2002
Contents 1 2
G $Bourne shell 2.1 + . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.1.1 shellÎ# . . . . . . . . . . . . . . . . . . . . . . . . . . 2.1.2 Æshell scriptsubshell . . . . . . . . . . . . . . . . . . 2.2 óÐóÿà;¶® . . . . . . . . . . . . . . . . . . . . . . . . 2.2.1 ó¸à . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.2.2 Srquote . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.2.3 ÀrÝóã . . . . . . . . . . . . . . . . . . . . . . 2.2.4 (ó . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.2.5 ×°/ó . . . . . . . . . . . . . . . . . . . . . . . . . 2.3 Ðó9jÿà; . . . . . . . . . . . . . . . . . . . . . . . . . . 2.3.1 ÿà;P . . . . . . . . . . . . . . . . . . . . . . . . . . 2.4 ¥²I/ú . . . . . . . . . . . . . . . . . . . . . . . . . 2.4.1 /ú . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.4.2 ²Iú . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.4.3 ó. . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.5 File descriptorI/O0' . . . . . . . . . . . . . . . . . . . . . . . 2.6 ø×?f . . . . . . . . . . . . . . . . . . . . . . . . . 2.6.1 ?f . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.6.2 if f¾\ . . . . . . . . . . . . . . . . . . . . . . . . . . 2.7 2.8
2.6.3 for loop . . . . . . . 2.6.4 while loop . . . . . . 2.6.5 case switch . . . . . Portable Shell remote shell . . . . . . . . . . . . .
+
. . . . .
. . . . .
3 Regular Express 3.1 -RE glob . . . . . . . . . 3.2 . . . . . . . . . . . . 3.2.1 . . . . . . 3.2.2 3.3 . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
+ . . . . . . . . . . . . . . . . . . . C- § . . . . . . . . . . . . . . . . . . . ÃÍC-î . . . . . . . . . . . . . . . . . . . C- § ÀrPî . . . . . . . . . . . . . . . . . C § !Àrî . . . . . . . . . . . . . . . . . . . 3
5 7 7 7 9 11 11 11 11 12 13 14 14 14 14 18 20 22 24 24 25 27 28 28 28 29 31 31 32 32 33 33
CONTENTS 3.4 3.5
CONTENTS
Pë(address) . . . . . . . . . . . . . . . . . . . . . . . . . . greedyÝregular express . . . . . . . . . . . . . . . . . . . . . . .
4 sed 4.1 . . . . . . . . . . . . . 4.2 addressing . . . 4.3 pattern/hold space, regex 4.4 sed command . . . . . 4.4.1 . . . . . . 4.4.2 pattern/hold space 4.4.3 . . . . . .
+ Ð)fÝ
ú Ãͼ ×M
9
. . . . . . . . . . . . . . script . . . . . . . . . . . . . . . . . . . . . . . . .
f
5 awk 5.1 . . . . . . . . . . . . . . 5.2 script . . . . . . . . . . . 5.3 . . . . . . . . 5.3.1 . . . . . . . 5.3.2 awk shell . 5.3.3 Array split 5.4 . . . . . . . . . 5.4.1 . . . 5.4.2 if . . . . . . . . . . . . 5.4.3 for loop . . . . . . . . 5.4.4 while . . . . . . . . . . 5.5 function . . . . . . . . . . . . 5.6 . . . . . . . . . . . 5.6.1 -match 5.6.2 print(f) . 5.6.3 rand() . . . . . . 5.6.4 system() . . . . .
+ à óû § /ó ó ó p Ðó ÃÍ×+° ó.ìÕÐ
ÍÐó C § ð íáí § Bó Ù
6 perl 6.1
6.2 6.3 6.4
6.5
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
35 35 36 36 37 37 39 41
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
45 45 45 46 48 49 50 51 51 52 52 53 53 54 54 55 56 56
j
Ý §
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
ÃÍ+°£]lV . . . . . . . . . . . . . . . . . . . . . . . . . 6.1.1 ó . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.1.2 f× . . . . . . . . . . . . . . . . . . . . . . . . . . . ?powerÝregular expression . . . . . . . . . . . . . . . . . . . . . ðàÐó . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Ù § . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.4.1 process . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.4.2 jn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.4.3 system call . . . . . . . . . . . . . . . . . . . . . . . . . . module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
u`Äò·®
34 34
57 57 57 58 58 58 58 58 58 58 58
CONTENTS
CONTENTS 5
C+°f´ ó . . . . . . . . . . . . . . . . . . . . . . . . . . . . p . . . . . . . . . . . . . . . . . . . . . . . . . . . . fB . . . . . . . . . . . . . . . . . . . . . . . . . . . . ff´ . . . . . . . . . . . . . . . . . . . . . . . . . . . ]º× . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]º . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P . . . . . . . . . . . . . . . . . . . . . . . . . . . . Û . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7 Bourne shell, perl 7.1 . . . . . . 7.2 Hash . . 7.3 . . . 7.3.1 7.4 . . . 7.4.1 while 7.4.2 for loop 7.5 . . . . . 7.6 . . . . . .
u`Äò·®
59 59 60 61 61 62 62 62 63 64
CONTENTS
u`Äò·®
CONTENTS
Chapter 1
G
Í@ÎbàÃÍÝ Ì9¯Í@ê µXÝ x 3 ( îÝ v|IYP¶® lPݶ®
« %®ç°%® KàÕscripts #ô|à ¶Í ÷ X| ÎtÃÍGÍ@Xt ¶ÙõTàPÝ º/lVÝ Õθàé\Ýt{(&Ý scriptÍ@×ßÿºàÕA ®î^broutineÝ ® # I5ÝßÝé\
ºàÕ»AÑ;×SZaTïi% xÎ9° ® Îðð3ÿ×ÍgeneralÝ!J »A&àscriptÞ?ÿÕÝ£] ¿àgnuplot®x-y`a% ×ߺ- 9jìàExceliÎ ®ÞÎ×ß×O
« ©Í¿g9˯ଫ¬ô^ð9K ` ¬ÎAðð®? §9g`×ßôºàº/(macro) Ñword, excel macro 9Í@µÎ×Ëscript scriptsm_ËX||"ݶ¼Ñ; C/C++m§ºB7 Ý®Þ scriptsµ BASIC+Ý¥3ßv¤Ýóµ?C/C++µ 3£\.£]3 B7É¼É à+µÎÝ¥3CPU/ÝºÕ - registers9Ít&µ Î&Í5·Úx¼Ý»A/׺à J̬^b9°ÃÍ ÌôµÕºJ̧̣ø¼ Ý?? N×·Kµäì«×·Ýèºinterface¼¸àQ¡èºî׷ݸ àï interfaceN×·N×·KbÝX|Einstein1ݵÎIYbôÝ Ò«Ä t&§ßÝÃ100Ob×ÍßÏ X|scripts3Ñ;õ ×°routine jobb">ÝÄP Again! A¯Ýé\ÃÎ?9\bݯº:ÿÆÿp ô0ÕÝ£G»A.profile .bashrc9Ëj( 9Î ºÝ.ïÝÄA¯9×FÝÌFT9S ZaE¯bX Qà scripts scripts ” ” configuration Makefile package System Admin perl scripts server scripts script
7
CHAPTER 1.
u`Äò·®
G
Chapter 2
$Bourne shell 2.1
+
2.1.1
shell
Î#
shellÎ×Í#å¸àïú¡O®¼ÙÆÝ×ÍTàPbߺ .shell ii3kernel²«Q¡3×·AP&f´Q!9Ëi°¦ E y&¼1shellô©Î¨²×ËapplicationPÍ@¸«gimp, netscape Î×øݩκlogin§¼X|Î|ðÝ×ËTà P àC program¼9ø|Q¯Ý(ó
9
2.1.
+
CHAPTER 2.
$BOURNE SHELL
bash USER
-
0x000
exec
ls
0x000
USER
- subshell
bash USER exec exec
exec
KERNEL
0x000 KERNEL
4GB
4GB KERNEL
4GB-
cp
USER
-
0x000
rm
USER
0x000
KERNEL
4GB
- ENVIRONMENT
VARIABLES
KERNEL
4GB
u`Äò·®
CHAPTER 2.
$BOURNE SHELL
2.1.
+
11
¶×wshellÍ@&ðxÎRÕuserÆÝú¡àforkþ¨ ×process Bunix likeÎ9ß9 ÝQ¡39Íchild processàexecÆ 9Í ²IP»Als, rm...X|shell/Iݺ®ÃÎ9øÝ 1. shellP×"8ÇK 2. Æprompt¸àïíáú 3. RÕ¸àïíá 4. fork()×ͱprocess 5. exec()ú 6. Æ9Íúê/Õshell 39\ º:Õunix likeÝÆ×ÍPK΢ãexec9Ísystem call¼Æ Ý 9ή¼Ù躸àïPÆPÝ^×system callÎuserP «kernel Ú;Ý°×Ѽ 3|GMS DOS`×^¡ºÆcommand.com9wPµÎshell µºþ C:\>
¸àïíáú9ÍC:µÎèîÐr(prompt)bourne shell;ðpromptÎ$ ©Ä9Ídos shell8 Ý-X| `bÍb(Ý4DOS9Íshell| ã (4DOS9ÍshellÍ@JÝ9unixîshellÝ©P Q«ËÝunix shellÎ f) A ©Îà¶×¶×°icon¡¼ÝMS-Windows` XÝ`Ý command line shellµ%;Ý+«ãÝÄÆ¨× ÍPÝ^×Î× øÎexec() unix like ÝÙÝúøPÝshellÃÍîtÝƲIúx| ”Õ”×°C¼Æ9°CscriptÝ? Î|'×°( .9Í ²Iú/)R¼W× ® »A3Windowsì&Æôº'TMPDIR9 øÝê¼Õ£Íêb°windowsP º.ÆÝ×°õ`jnw3 9
unix likeÝshell scripts+°|bif, while, for loop¤g×°²I ú|½(!`b!Ý' ¸ÿ×°^ð ®î?ÿTT WfÝdos shell? ú sed, awk....9°²I ÌòòBÕÎýãÝunixÙÄnÝú ̵ winzipWNÍwindowsKºÝ Ì9 ÌÕÎWZÝ / BÃshell programming ÌÝ 2.1.2
Æshell scriptsubshell
ËË]° • R±shellÆshell scripts u`Äò·®
2.1.
+
CHAPTER 2.
$BOURNE SHELL
3êGshellÆshell scripts R¨×Íshell¼ÆÝscripts3scriptsjtG«G •
#! /bin/sh
Ï×Ë]°Î3shell script ZCjG¼shell scripts\ÝP3£(ôµÎ &ÆÝshell)Q¡.ZCjÝÆJ§Æï×ÆÆj]PÆTï § ×Íshell¼ÕZCjtest.sh $ $ $ $
test.sh /bin/sh test.sh ( . test.sh; ) exec test.sh
ÏÞË]°Îàú”.”TïsourceÆ $ $ $ $
. test.sh source test.sh { test.sh; } eval ’. test.sh’
-½3y×°'©b39ÍshellìÝÕóR¨×ÍshellµÎ¨×Í 8Ýt& ôµÎàÏ×Ë]°ÆÝscriptóÝ'ºÅ( Õæ¼Ýshelló 9Í8 ¥ksh^bsource9ÍúX|t? àsource Àr( )îà¨×ÍsubshellÀr{ }îàêGshell»A $ ( VAR=’testvar’; ) $ echo $VAR $ { VAR=’testvar’; } $ echo $VAR testvar
©b{ }/ÝVARÝÂ'Íà . Ý]°T 3script
« à $ . test.sh arg1 arg2
. arg1 arg2ºµYñ§9ÍscriptÝarg1 arg2¼à . Ý]Pt?ÎÆ Ýscript©Î×$script libraryñ¢ó ¨²A . test.shÆtest.shÒ `ñ§. test.shÝshellô«½Ò u`Äò·®
CHAPTER 2.
$BOURNE SHELL
2.2.
ó Ð óÿ à ; ¶ ®
13
ó Ð óÿ à ; ¶ ®
2.2
ó¸à
2.2.1
óÂà
var="value" var=’value’ var=‘command‘
.ÂJ¼ÍþÐr$ $ $ I $ $
var="I am a gyoza" echo $var am a gyoza var=‘ls *‘ echo ${var}
$ var=’$var’ $ echo $var $var
|î¥ÝÎè}Îb-½ÝbSrÝ!®à?ì: 2.2.2
Srquote
2.2.3
ÀrÝóã
"8îÝdouble quote, single quote, backquotez½ • backquote ‘command‘ 9ÍÎúãy $(command) X|ðð :Õvar=‘commandTïvar=$(command) µÎ.commandÆ' var • single quote 3’ ’/ÝZC;;1¹æøðb°1ºÐr3S r /1º©L • double quote 3” ”/ÝZC$ ‘ ”ëËLºð͸Ý1¹æø • escape char 3\ ¡Ý×C-ô|1¹æø
îÀr{}ÎparameterÝ]° ${var}Îf´?ݶ°A^bÍ C|à$varµ? Tè}Îb-Ý ÍP¶®9è×Í Kè×}Îb-Ý Íó×°à° • ${var:-value} AvarbÂÝ£µàæÍÝÂQàvalueÝ • ${var:+value} AvarbµàvalueÝ u`Äò·®
2.2.
óÐóÿà;¶®
CHAPTER 2.
$BOURNE SHELL
b£µàæÍÝÂQµmessage ÂÕÇ
• ${var:?message} var
K¬v®
• ${var:%pattern} var
I
• ${var:#pattern} var
I
Apatternvar¡«ÝI Ù)F/yì^b Ù) ApatternvarG«ÝI Ù)F/yì^b Ù)
• ${var/pattern/substitute}
:×Í»
AvarbpatternÙ)µðWsubstitute
ºy
# remote shell $RSH /usr/bin/rsh RSH=${RSH:-/usr/bin/rsh}
ARSH ^bÂ
9Ë]Pà3bPÝoption?à |ì«9ÍP » AF¢óJ W"-o ¢ó"^b¢óJVAR^b ÎÏ×ÍF ¼Ý¢ó AbÂVARµà"-o $1"
# :+ # # VAR # $1 func() { VAR=${1:+" -o $1"} }
9Ë|à3[ãCÝØI »A TïbÝúã/Ý??ÎE5( ¬&Æ©t¡«Ý£Íjn(`|à9ͼ[ã ÄFÙÝ ^b% # pattern match9©b3 b t?à;àsedf´1 ×F
# :% # find # # bourne shell # ksh bash
PRIV_HOST=fermion-priv PUB_HOST=${PRIV_HOST:%-priv} echo $PUB_HOST (PUB_HOST fermion)
ºy # ðôÎ 3±ÝKorn shellBourne Again Shellîb BLOCK_DEVICE=/dev/vx/dsk/oracledg/vol_0 RAW_DEVICE=${BLOCK_DEVICE/dsk/rdsk}
2.2.4
(ó
û;Ýó ABourne shell, korn shellìà $ export var
u`Äò·®
CHAPTER 2.
$BOURNE SHELL
c shell, turbo c shell
2.2.
ó Ð óÿ à ; ¶ ®
15
à
$ setenv var
J9ÍóµW×Í(ó3C
«Ý main(int argc, char **argv, char **envp)
&Æ|3shell
'(ó9ÍÂÎNÍã9Íshell forkÝP BãenvpK:ÿÕÝ9Íargv, envp¼ÝK3virtual memoryÝì«stack ? îÝ :k®”àOpen Source toolss8” X|shellôÄ Î×Í”User spaceÝC program”(ó3C image user spacetì« ô|getenv9Ílibrary function callJÕ X|× 'ó^b' (ó^bð°.Â×å͸ÝP 9\¥ÝÎæÍÝBourne shellÝexport^bYî $ export var=value
ݶ°X|:Õ×°shell scripts ÝportableRKà $ var=value $ export var
2.2.5
×°/ó
G×ÍúÆÝstatus 0î^®Þ3P'
0 îFALSEôîNo ERRORX|PÝexit return §? • $# îFshellÝargumentsó • $0 9Íshellú(C • $1 $2 $3 ... functionF ¼Ý¢óarguments • $@ îfunction F ¼ÝXbargumentsºy ”$1” ”$2” ”$3” • $* îfunction F ¼ÝXbargumentsºy”$1 $2 $3” • $$ îêGÝprocess ID 9\$@ $*Î×øÝTsingle guote, double quoteÝ×ø $?à3? fݾÎtðàÝ shell×ôº'×°/(ó9°(óºb×°Pº ¼\ã »AmailPàÝMAILb¼úX3¨´êÝPATH 9°Î¶bash, ksh, cshÝC׶3CP/Ý :(óàenv9 Íú:óàsetúµ:ÿÕ×ø u`Äò·® • $?
2.3.
Ðó9jÿà;
2.3
Ð ó 9 j ÿ à ;
CHAPTER 2.
$BOURNE SHELL
ÐóÝLà#µÎ func() { cmd cmd ... }
FÂôÎ×øݼ§$1 $2 ...$@ à°Î×øÝ ñ§`µÎ func arg1 arg2 ...
¥ÝÎóÎ^b C×øÝblocal variable;;ÎglobalÝ ÝperlôÎ9ø 2.3.1
ÿà;P
functionÎtÝmodulized¶®¼µÎ9Íÿàj Wshell libj à Ý9ÍjݮޫCÎ×øݵÎó§ø3×ÍjLÝQ¡¯½Ýj ¢ï ;ðexport W×Í(óTïàeval9Í/IúÆ×ÍÍshell script¸ÿ 9óÎK:ÿÕÝ
2.4
¥ ² I / ú
&ÆðàÝls, cp, sh....9°KÎ×ÍÆj8Ey×ͲIÆ j shellb×°/Ýú3shell
«9°Îbuilt-inÝ/IúÎ àC¶ shell9wP`µ¶3
«Ý cd, export9µÎ bashÍ@b9|GݲIúKâ ¼®W/IúÝ»Aecho, getopts Ä ÝP÷P&ÆÎ.ÆÌ ²Iú9°/ú |àenable, disable3bash/ã*ĽÝsh, kshT&µ^bÝ T 2.4.1
/ú
f´¥vp×FÝ/úb • : ¼#K®yCPU/ÝNOP¼ • eval I5༮Ëgóð • exec ÆØËú¬vð*êGshell(æÍÝƺð*shell) u`Äò·®
CHAPTER 2.
$BOURNE SHELL
2.4.
¥ ² I / ú
17
ÿÕ¸àïstandard in("8)íá • set shellÝÞÞ'»Adebug shell scripts • test shell scriptsÝ×+°/Ý?f • trap #ÕØËGrÝ § • shift argumentsÝ § : magic numbers Û :΢¯Ý3UnixÙÆPºlãjnGÝC§ magic numberÝBourne ShellÝÆmagic numberÎ : Î #! X|:Õ9Ë |:Ýshell scriptµ¤QR¯!`:ôbßJ¼®Ûà à#Ý 9°êYÝshell scriptKÎÝ eval ñ ^ C eval|J¼Æ×ÍúÄtðàÝÎJ¼®ËgóÝð x ÎNgÆ×Íshell úºevaluate×g:Õb$9Íݵ.Âð× g.óð* Q¡Æ×Å9Ëdouble scanÝ]°E×°óðb à . evalÎR¨×Íshell¼ÆÎ3ͼ9Íshell/9evaluate× g X|ð|1ºì¼ »AA&ÆËgð • read
count=1 var1=I var2=am var3=a var4=gyoza while [ $count -lt 5 ]; do eval "echo \$var$count" let ’count=count + 1’ done
|×à;1. 2. 3 ....®ß×ͱóvar1 var2 var3....Q¡E var1 ãÂÍ. Ï×ÍvarºÕX|àescapeC-\ Q¡ÏÞ gºÕ`Õ £Aëg|îóð3×/X÷? :Ï evalxà¼evaluateÆ×Íshell scriptj| C×ø¶W9Ý ÿ àshell script3!×ÍshellìrunJó3hshell/;;b[ count var2
$ eval ". foo.sh"
ÄAóH9(CºÆÚ u`Äò·®
¥²I/ú
2.4.
CHAPTER 2.
$BOURNE SHELL
exec
º. êG Ý JÍ J*ðW¡«ÝúÍ@9µÎà 9Í Hð*ÝLÎ×øÝ tð:ÕÎ3 /.xinitrc9 Í Hð*W »A exec twm X|A¯3shell Æ exec ” ” shell process exec() system call scripts window manager exec cmd
cmd9ÍúD3µº/Õlogin. JÍshellðÕcmd¬Q^ bcmd9ÍÆj X|ÆPÝ]°ËËÎ×øÝ $ exec cmd $ cmd
w3scriptsÝÆ Qô×ø Äexec3scriptb¨×Í8 ¥ÝàHµ Ϋfile descriptorÝ= 9Í쫼D¡ read $ read input read from standard input $ echo $input read from standard input
Jº39\"8íáíáCW$input9ÍóÝÂ set set
ÎJ¼'9ÍshellÝÆ(Ýf´¥ÝscriptºàÕÝà • set -- Ñð:Õ-¡«Îoption¨3Îoption Î×Íú¢ó A-1 -2 ... • set -a 9\|¡óW(ó • set -f Õj(Ý©C-»Awildcard *Õ XbÝ¤Ý • set -x debug shell scripts
×àexitÒshell,ͼ¶Ctrl-D(eof)ô| • set -o noclobber n*I/O0'ãoverwritejn • set -o notify shell@` ×background jobÝstatus • set -o noglob n*wildcardC-Õ A * ? [ ] • set +o .-oÝD'E® u`Äò·® • set -o ignoreeof
CHAPTER 2.
$BOURNE SHELL
2.4.
¥ ² I / ú
19
n*-v -x –ëËó4 set -- Tïset - ððà3shell scripts
« set -o ÎðàÝ»Aset -o vi'shellÝE®]Pàvi]° ã/îÍúµÎ¶ESC¶kC set -o emacsµÎàemacsÝ]° • set -
test test
Î×+°Ý?f9Í3ì«D¡
trap
RÕØÍsignal`shellÝET ;P $ trap "command" signo ÍsignoÎ 1) 5) 9) 13) 18) 22) 26) 30)
cyril@grill:~$ kill -l SIGHUP 2) SIGINT SIGTRAP 6) SIGABRT SIGKILL 10) SIGUSR1 SIGPIPE 14) SIGALRM SIGCONT 19) SIGSTOP SIGTTOU 23) SIGURG SIGVTALRM 27) SIGPROF SIGPWR 31) SIGSYS
3) 7) 11) 15) 20) 24) 28)
SIGQUIT SIGBUS SIGSEGV SIGTERM SIGTSTP SIGXCPU SIGWINCH
4) 8) 12) 17) 21) 25) 29)
SIGILL SIGFPE SIGUSR2 SIGCHLD SIGTTIN SIGXFSZ SIGIO
»A
$ trap "" 2 $ trap "rm $TMPFILE" EXIT 1 2 15
A””ÝcommandJîshell §9Ísignal 2rµÎINT;ðµÎ¶ÝCtrlCÆ\shell scriptÝÆ15µÎ TERM(processkillÝ):p×FÝ» trap_init() { trap ’
scriptcleanup [ "$SCRIPT_DISP" = ABORT ] && exit 100 [ "$SCRIPT_DISP" = PASSED ]; exit $?’ EXIT if [ -z "$__TC_INTERACTIVE" ] then for sig in HUP INT TERM; do trap " trap - HUP INT TERM; echo ’Signaled - cleanup after script ...’ >&2; scriptcleanup $sig; kill -$sig $$; exit 101" $sig done fi trap : PIPE
u`Äò·®
¥²I/ú
2.4.
CHAPTER 2.
$BOURNE SHELL
}
9Í»ÝG«A8ÕEXIT9ÍsignalµÆscriptcleanÕexit $?Ýcode µÎquote/Ý A$ TC INTERACTIVEÎèCµÆì« Ýsignal § t¡AÎSIGPIPE(13r)µ¢¯(Ar:) shift
Îà¼. ¼ÝargumentsÉ×ÍÉ shift n ÉnÍÉ shift|J¼ àøÄ10Í|îÝargrments. $1 ... $9©b9Í ¼:×ÍshellÝqueue listÝappend shift
# list_append list_name item ... - append items to a list list_append() { _list_a_name=$1; shift eval "set -- \${$_list_a_name} \$*" eval "$_list_a_name=\$*" }
2.4.2
²Iú
b°²IúðàÕ • basename J*j(Ý § • echo messageÝ]° • find 0jn • getopts §F ¼Ýarguments«CÐP0Ýgetopt() • xargs pipe`ÝúÆ¢óargumentsÝ § ¨²sed awkºbÝ+Û basename
Rj(j( Ì $ basename foo.c .c
Jj( .c º* u`Äò·®
CHAPTER 2.
$BOURNE SHELL
2.4.
¥ ² I / ú
21
echo
ÎÕÇKÝWð(ôbprint, printf|à) 9\ýÝÎsh, /ÝechobashÝ×øX|'b°×ø echo -n "messages" ð(newline) echo -e "messages\c" ÕescapeC-\cy-nà° echo -e "\t messages" tab3messagesG
echo ksh
FÙsh, kshÎ^b-n -eó4Ýà#àechoµ? echo "messages" ð(newline) echo "messages\c" ÕescapeC-\c ð(newline) echo "\t messages" tab3messagesG getopt
getoptsÍ@Îksh, bashÝ/IúgetoptÎËݲIú 9 C
Ýgetopt():Í» while getopts :dvt:n: c do case $c in d) DEBUG=yes ;; t) TYPE=$OPTARG ;; n) NUMBER=$OPTARG ;; v) VERBOSE=’yes’ ;; esac done
ÍAr:Î19Í¢ó×b«½Ý¢óÂ^bAr dvî¡«^ bñ½¢ ó »Atð:Õ-vÎ1PÆ`Îverbose modeµÎ9ø $OPTARGµÎ«3¡«Ý ¢ógetoptsQ& §?¬v×Í×ÍÝó
$OPTARG¼ôb$OPTIND«C libraryÝà° find
´0jnàÝPú u`Äò·®
¥²I/ú
2.4.
CHAPTER 2.
$BOURNE SHELL
0 0 0 0 0 0
find . -name "regex" find / -type d directory f plain file l symbolic link p named pipe file b block device c char device find . -perm 755 find / -user cyril gzip ‘find . \! -name ’*.gz’ -print‘
not !
bÝshell\ . !b©½L»Abashîã/|GÝú
find -name -type -o -name
3script9`ÎKÎñ^C-®Þð:Õ\`KÕ9Îñ^C- 3script ()ôb©½LîR¨×Ísubshell¼ÆX|$Õ()`ôà ñ^C-Tï)sed awk×R¸à`ôÎ×øݼ§ xargs
༠§×°í¼ ¨×ÍíáÝarguments$ÕÝ®Þ »A
xargs
# find /usr/include/ -name "*.h" | xargs -n 2 diff
μbËË WíWdiffÝargumnets
-n2
# find /usr/include/ -name "*.h" | xargs grep ’#ifdef’
Ñð/ÎíÝ×rZ8Ýbàxargs`Î×Í×Í;¡«Ýú # find /usr/include/ -name "*.h" | xargs -i cp {} ~/include/ -i { }|.findÝíÝN×Í WcpÝÏ×Íargument /.µ| WÏ ÞÍargument Í@find
«b-exec9Íó4¡«ô|à{ }î×Í×Í ;¡«PÎ ×rZ0Ý;¡«P # find /usr/include/ -name "*.h" -exec cp {} ~/include/
2.4.3
ó.
xÎJ¼®counterÝb9Ë]°ì«+ÛëË bashbÍ/ Ýlet »A u`Äò·®
CHAPTER 2.
$BOURNE SHELL
2.4.
¥ ² I / ú
23
let ’x = x + 1’ let ’x = x * 1’
¥!!9\r\ÝxãÂ`àþÐrv3quote/ô|bè } kshôb/ÝÄ9ÎNËshellKbÝ f´1 Ýportable®° Îàexpr9ͲIú :» if [ "$KSH" ] then eval ’ add() { result=$((${1} + ${2})) } sub() { result=$(($1 - $2)) } mul() { result=$(($1 * $2)) } div() { result=$(($1 / $2)) } inc() { eval "$1=\$((\${$1} + ${2:-1}))" } dec() { eval "$1=\$((\${$1} - ${2:-1}))" } ’ else add() { result=‘expr $1 + $2‘ } mul() { result=‘expr $1 * $2‘ } div() {
u`Äò·®
0'
2.5. FILE DESCRIPTOR I/O
CHAPTER 2.
$BOURNE SHELL
result=‘expr $1 / $2‘ } sub() { result=‘expr $1 - $2‘ } inc() { eval "$1=\‘expr \${$1} + ${2:-1}\‘" } dec() { eval "$1=\‘expr \${$1} - ${2:-1}\‘" }
9î«LÝ×°P|3script
«×ø ñ§×úñ§ Î×ÍsubshellÆ1+1¬vF/ì«»¯&R&Ýbasic P $((1+1))
i=0 while [ $((i=$i+1)) -lt 10 ]; do echo $i; done
Ä$(( ))9«${VAR%value}×ø©bksh bashbt?à3m portable ÝshellPî PÝposition parameters $1, $2 ....«¿ðscriptPæJ ×ø A?9Ýó.»AóFݺÕTïsin logÐó¸à µàbcõawkÏ kshbashKYîtypesetÄFÙÝsh¬Yîbashbdeclare9Í/I ú 9ËÍKÎJ¼L9ÍóÎ#P²Ý CÝ
×Ä Ýportableà µàÎàtÃÍÝshµ?AËݶÿÓ µàperlÏA&ðÝ ¯µàCC $ typeset -i int_var $ declare -r constant
'WJóACJint varݺÎ0Aà-r JconstantÝ ¨3R;Ý
int var
2.5
File descriptor
I/O0'
×ÍPtÃÍݺ@ëÍjE®`8ETÝrµÎfile descriptor Í@ôµÎ®¼ÙNgÕÝfile descriptorÎper processÝ • 0 standard input ;ðµÎ"8 u`Äò·®
CHAPTER 2.
$BOURNE SHELL 2.5.
I/O0'
FILE DESCRIPTOR
25
;ðµÎÇK buffer I/O • 2 standard error ;ðµÎÇK &Æ|àI/O0' • 1 standard output
$ cat file1 > file2 $ dirs 2>&1 > /dev/null
Ædirs`X®ßÝstandard erroróÕstandard outÕAü/dev/null µ Î#ô:Õ exec tðà3file descriptorÝnÐ9
$ $ $ $
exec exec exec exec
3> $LOGFILE 3>> $LOGFILE 2>&< infile
Í&L5½ ×Í3rfile descriptor8Ey$LOGFILE.standard errn* .êGshellÝstandard inputWinfile $ cat something >&3 $ read <3
¨3 9Í µ8Ey ÝX|cat somethingÝ/ºÕ ¥ 0'ÐrÝè} ×°¥ÝI/O0': > ¥±0'¬v.jnéè(&ËÎ?:-)) >> .0'¬vappendÕjn¡ < ¥±0'standard input >&n .standard outófile descriptor n <&n file descriptor nJstandard in >&close standard out <
¥ÝÎb°¡«©#jnbÝ#file descriptorb #file descriptor`bè} ftpÝscripts3\\|G .ÝftpìÎ b(ÝXçì Ä©º3 wêÝDãX|&Ƶ§é\3 `cron jobQ&Æftpbb #!/bin/ksh # A script to automate FTP transfer HOST=ftp USER=user
u`Äò·®
2.6.
ø×?f
CHAPTER 2.
$BOURNE SHELL
PASSWORD=password FILENAME_PATTERN=remote_files REMOTE_DIR=/usr/doc LOCAL_DIR=/usr/local # -i = non-interactive, -n = disable auto-login ftp -i -n <
¥<<Ýà°ftpÝinputº×à\ÕHERE copen, user, cd, mget K ÎftpÝúÄô|. 9°ftpú¶W×ÍjnQ¡ftp < jnô
ø×?f
2.6 2.6.1
?f
3Bourne shellÝ/Iú
«b?fÝ+°testif whileà Tï
test condition [ condition ]
Ýautoconfprogrammerf´Kàtest àÀrconditionÝ ]°ÀrÝà°¥è} »A jn?f test -f /etc/file jnÎÍ×jnÎÍ©jn[ [ -e file ] jnD3[ [ -d /etc/ ] êD3[ [ -s file ] jny0[ [ -r file ] jn\[ C?f [ "$string" ] stringbµ/true [ -n "$string" ] stringb(non-zero)/true [ -z "$string" ] string^(zero)/true [ "$s1" = "$s2" ] s1 y s2`/true u`Äò·®
CHAPTER 2.
$BOURNE SHELL
[ "$s1" != "$s2" ]
óÂf Tb9Í-
[ [ [ [
$num1 $num1 $num1 $num1
-eq -ne -lt -ge
$num2 $num2 $num2 $num2
] ] ] ]
s1
2.6.
ø×?f
27
y s2`/true
num1
8 num2 true num2 true y num2 true yynum2 true
9¥f
[ ! -f "testfile" -o ! -r "testfile" ] [ test condition -o test condition ] ! not -a and -o or
î î
î
;ðf´ðàÝêbportableݵÎî«×°à° YÌî¼1àÀrconditionf ´?:9ß ÝautoconfÝ+°portableR ¼àtestݶ°?Ý Qw3$?0îW ÍÂî´? 3shell scriptôb:Õbßà if [ "x$VAR" = "xvalue" ]; then .....
¼®$VARÎÍÎèÝ?LͯA?ÎÍ èC ?Î£Í Â%9øµº®Ëg?¼à9ø®f´Bz ¨²9«perlCóÂ?|«perlâ?8Dvperl^b9perl+° if ($str1 eq $str2) if ($num1 == $num2)
t¡bÍf´º×Rshell perl cÝ-²¼(ßÝB&Î9ø B |perl ÃãeqÎCX|G¡Îstring==ÎÐrX|G¡Înumber bourne shellÎMhâ?xÅeqÍ-Ðr==K×Í=) C+° if (!strcmp(string1, string2)) if (num1 == num2)
2.6.2
if
f ¾ \
if test;then cmd1; elif test; cmd2; else cmd3 fi
u`Äò·®
2.6.
ø×?f
CHAPTER 2.
$BOURNE SHELL
if test then cmd1 ... elif test cmd2 ... else cmd3 ... fi
!ø¥¶W×`Ý5rHLÍ3¶Makefile`ºàÕ ¨²Ýelse ifÎelif «CÝelse if×ø ¨²bËÝifà° [ "$VERBOSE" ] && echo ’everything’ && îF/true`Æ&&¡ «® [ "$VERBOSE" ] || echo ’nothing’ || îF/false`Æ||¡ «® 9\bF¥ AÎèCF/false 9Í@ [ "$var" ]
[ -n "$var" ]
;ðÀr
«Î9°¾\Ý]P¬Í@NgA:ÕbúðÝP ºÆ×gú ¬ÎBÎC|3if while
«ÆP (expression)/return X/¼ÝÎúÝstandard outX| |½!`Æú Q¡¾\ÆWͼXì×M§® ÄbÝúWݺ3standard out ×ÀC&Æ|¿à9øÝ
¼ ®¾\»A [ "$(find . -name gyoza.txt)" ] && echo "I Find It !!!"
à$(cmd) yà‘cmd‘A0Õݺ9Íjn¼X|ÔSr
«” ”b  Àr µ/trueCA^bÔSr A©b×ÍCJº WCÕG true X| u`Äò·®
CHAPTER 2. $ $ 0 $ $ 0
$BOURNE SHELL
2.6.
ø×?f
29
[ 1 ] echo $? [ 0 ] echo $?
AbËÍ|îJshell.findó¼ÝCê WúƵs ß ý0Ý 2.6.3
for loop
for var in $list; do cmd1; cmd2; done for var in $somelist do cmd1 cmd2 done
¥¶W×`Ý5rHLÍ3¶Makefile`ºàÕ listÎshell
ðàÝ ×Ë]°µ©Î9àè}Ttab5Ý£]µÎ »A ME="I am a gyoza"
µÎ×Ílist(bashÝman pageàlistî×Àcommnands .wordî9
Ý bÝhTïksh, shÝman pageê×ø X|&KL9° (Þb`ÎÊ¡9°^bL RÕkey pointf´¥)for B|×g.× Í-ô;G«Ývar ME list
for ELEMENT in $ME do echo $ELEMENT done
µº¨ I am a gyoza
¥þÐr'ó¸àóÝ-² u`Äò·®
2.7. PORTABLE SHELL REMOTE SHELL CHAPTER 2.
2.6.4
$BOURNE SHELL
while loop
while test ; do cmd1; cmd2; done while test do cmd1 cmd2 done
!ø¥¶W×`Ý5rHLÍ3¶Makefile`ºàÕ 2.6.5
case switch
case $var in *)cmd1; cmd2 ;; xx?)cmd3; cmd4 ;; esac case $string in *) cmd1; cmd2 ;; xx?) cmd3 cmd4 ;; esac case $answer in [Yy]) echo ’yes’ ;; [Nn]) echo ’no’ ;; esac
Ýà° CÝÎJóÝcase switchÎ|bCÝ Í Ð)ÝCfàglobbingÝ]PôµÎwildcard *, ?, [ ] bÝhî ¶regular expressÎý0Ý¥à׶Ý]° case switch
2.7
Portable Shell
remote shell
remote shellÆÎËÝ.GÐÝstandard out =Õ Ýstandard out X| ×telnetP Í@A ®(@©3bashî£ôàÊ×°¬¿¬Ý Ä A®development`ÊÕportableݶ®TàtæÝshµ? u`Äò·®
CHAPTER 2.
2.8
+
$BOURNE SHELL
2.8.
+
31
×ýãàshellÎBourne Shell¡¼;¨Korn Shell9×ÄÝ / f´Kàkorn shell¶scripts¨²bBSDÝC shell c shellôCW×ô± LÍ39system admin¡¼tcsh 9ýÝ©F Bourne Again Shell.bÝ^Ý©FZZÚÚw3×R´GNU/Linux± OD×Ý /9KbashÄ¥portableÝshell scripts¶® sh, ksh bashÎ !×HÝ9¿Í+°f´# tcsh cshΨ×H -9× 1¼sys adminKàc shellFÙÝprogrammeràshÝ´9
u`Äò·®
2.8.
+
u`Äò·®
CHAPTER 2.
$BOURNE SHELL
Chapter 3
Regular Express 3.1
+-REglob
regular expressÎ×Ëî]°à×°©ÝC-¼î×°é\
Ý© L¬v ´0Ý×ËøPfE (pattern match) 3MS dos/windows ôb8 ÝC-»A * XbCX|¯àdel *.* µ|B *Xbjn* µ§wildcardC-Ä93shellÝ §©Î§globbing ¬Îregular expressÍ@9 QÎUnix.ÝUNIXîÝregular express?ú vÊày9Unix 8
« grep, sed, awk, vi, emacs perl... |1regular expressµÎ¸àUNIXÝ·~ ļ.unix.DOS£ generalÝ CP
« §regular expressAÎPOSIXÝÙJà regcomp() regexec() System VÝbregcmp(), regex()BSDÙbre_comp(), re_exec() 3shellÝpattern match§globbingshellÎ-ÿregular expressÝ ;ðà y5(Ý ? * [] ÝfEETàfnmatch()¼ § Ä9ÎÝ¥ F©Î|¡ $àC¶P`|Õà#function call ;ð9¸àregular expressÝ`¡ºà×E//ô /reg express/
¼î0Õ){reg expressfÝCperl
«1Í@Î m// s///
îmatchsÎsubstitudeÄm|6¯¶µW//Ý ;ðà° Îm//ú s///úúð:ÕÝb • p -> print ;ðôචm
33
3.2.
C- §
CHAPTER 3. REGULAR EXPRESS
9;ðΫ3mú¡ Ð)ݵB* • c -> confirm ;ðà3sú ®ÎÎËã • g -> global ;;ð . matchÕ`/©bÏ×ÍÐ)Ýb[ • i -> ignore Ѷ Äô× grepúµ^bàÔSrµ|Ý anyway,©Î9K Î9øî • d -> delete
3.2 3.2.1
C- §
ÃÍC-î
C-µÎ××ÍzZCÒÝ §¼ÍÃÍÝC• . ”×Í”C-tÝðnewlineC-Äawk|matchðB • ? ”G«”C-¨0gT1g • + ”G«”C-¨1g|î 1 2 3 4 ... ¨return false • * ”G«”C-¨0g|î 0 1 2 3 ... 9\.ïf´ðÙÝý0Î3shellìÝwildcard * ÝêY| ©Í* µXbC-Í@Î ? + * KG«¤g . ¼¸àC• ^ ´ • $ • \ ñ^C-(escape)ã©C-ÝLàÝ 9\f´¥ÝÎC3´RÝ^ Ý$3Ýcase5ò! Ýregular expressTbÝPº.9ëË W!Ýregular express 9º ×øÄbݺ • /^#/ b#3×ÝÏ×C-` µ/TRUE • /^bag/ bag3´Ý • /bag$/ bag Ý • /bag/ bag3 Ý ÄbÝP §^b9} sed • /b.g/ îbag beg bugK • /b\.g/ îb.g • /^..g/ î´bag beg bug xxgKÐ) ¬×ëÍCÒ • /^.*g/ î´b¢C-ÝQ¡bÍgÝK|/true u`Äò·®
CHAPTER 3. REGULAR EXPRESS
3.3.
C § - ! À r î
35
• /beg*/ be, beg, begg, beggg, ....... • /beg+/ beg, begg, beggg, begggg, ...... • / */
3.2.2
èçC-ô
C- § - ÀrPî
/Ý×”×C-”Ð)µ/TRUE • [^ ] []ÝD[ â[]/Ý××C- /true X|9\^3[]/ b!ÝL • [1-10] -r3[]/|î×ðPàÆÕWTi X|A î-rÄ6w3Ï×Tt¡C• w{n,m} =C-¨î° fà /.../?à «L T XÝtableÝà° îb”=”Ð) wC¨”=” ngÕmgE Kº/TRUE • 0{3,} 0K¨3g -> /xxxx000xxxxxx/ 3Cì{} ()ÎîËÝ9°C-Ý [ ]ºregular express W×Ë ºÕX|Ýàñ^C- W\{ \} \( \) • [ ] []
A
3.3
C § - ! À r î
×°CÝ §î
• ( ) Group operator
Tï Tï Î Ý ©b×°8AegrepbYîX |3à8Ý `Ä6á¼ §Ý æ • & î0ÕÝC • \1 \2 \3 ... s///G«àÀr\(\)ÀR¼ÝC 9;ðôÎ0 ÕÝCÄ&©b×Í à \1 \2 \3 |b9Í \1 Ï×ÍÀr/C \2 ÏÞÍÀr/C ;ð\1 \2 \3Îà¼EmatchÕÝC §`àÝ /[Yy]es/ Yes õ yes /80[23]?86/ 8086 80286 Tï80386 /[A-Za-z0-9]/ C-|b9øÝ=î° /compan(y|ies)/ company companies /0\{3,\}/ î0¨ëg|î u`Äò·® • (str1|str2|str3) str1 str2 str3 () | extend regular expression regex regex
3.4.
Pë(ADDRESS)
CHAPTER 3. REGULAR EXPRESS
ÞæÍÝîÀr .ËÍCE ¥\1 \2Ýà° Í 9°ðà3ð(substitue) ¥Àr3G«b!LX|Ä6à\¼escape
s/.*/(&)/ ( ) s/\(str1\) \(str2\)/\2 \1/ & \1 \2 \3 ...
3.4
Pë(address)
3sed, vieditor
&Æ|¼ §ÝP 9˼ §Ýf TØðrangeô§address(ë) LÍÎðúðà range(addressing)s///
sed $ sed ’1,3d’ file
3Ï×ÕÏë *J
vi :%s/xx/yy/g
.JSZaÝxxðWyy
ðàÝPÐr • , ó§× 1,5 îÏ×ÕÏ" • 0 tî× • . êG • $ t¡× 5,$ îÏ"Õt¡× .,$êGÕt¡× • % JSZaôy1,$ • x-n x?îón .,.+10 îêGÕêGè • x+n x?ìón 3.5
greedy
Ýregular express
XÛgreedyÎ1A×
«Ð)regular expressionݵb9ôµÎ ! `b9patternKÐ)`;ðº1TÝÐ)tÝ£ÍpatternÄ ¬ Î&ÆÝLÍ3HTMLÝtag §î»Aà/t.*t/0
this is a tag3 !×
b
ôbgreedyÝ §©bperlbf´Ý] °9Þ3perl
«Õ
u`Äò·®
Chapter 4
sed 4.1
+
Î×ËStream EDitorôµÎ;¸×£]ø«úW_ìÝ® 9Ê);Ýscripts®¼ sed
file -> stream -> sed -> stream -> file
ãy¸Ä6bÍin §¡bÍoutX|!`;Íjn Ä6 § jn¡XW±j(.jl*.±j;(Wj ê. /í Îstandard outX|ð:ÕÝ]°Î $ sed ’sed_syntax’ old_file > new_file $ mv new_file old_file
Äsed;ðÎà¼ECÝ §îÎ ×editor¼modifyjnÝ vBÎ×× §ÝX|èç, tab, ð9°C-¥ sedÝ×PÎ sed [address],[address][!]command[args] file
Íaddress,commandàSr’xxx ’ addressµÎî«regular expressÝ ðàÝúbd(delete), s///(ð) ×°» $ sed ’s/yes/no/g’ file .jnyesðWno $ sed ’/save/!d’ file .^bsaveC¿Ý* $ sed -e ’s/\(.*\)\(#.*\)/\1/’ xxx.sh .#¡«ÝÛ* Í-eÎðàÝ×Íoption;ðÎà3ËÍ|îÝó4` Íãy( )b ©½LX|mDEaescape×ì 37
4.2.
4.2
Ð)fÝADDRESSING
CHAPTER 4. SED
Ð)fÝaddressing
addressÎsed
Ý©à+à¼'Ð)fÝ|-E¸Æ_ìú Ð)fÝf¼]°b1. range(P) 2.regular express sedÝaddresstÝGregular expression+ÛÝ 1,3 . $ %9Ëî°² |à#à /regex/0ÕÝ $ sed ’2d’ file 0ÕÏÞ* $ sed ’/delete/d’ file 0Õdelete9ÍC*J $ sed ’/RE/,$d’ file bREC¿ÝÕjn ;;* $ sed ’/^$/d’ file *èç $ sed ’/START/,/END/!s/xx/yy/g’ file > file1 .xxðWyy
4.3
pattern/hold space,
AbËÍf|î£|-e
9regexfscriptj
$ sed -e xxxx -e xxxx file
»AÞÛWèçQ¡B*Xbèç
$ sed -e ’s/\(.*\)\(#.*\)/\1/’ -e /^$/d file xxx.sh sedÍ@NgK.×wÕpattern spaceQ¡EE® Æw Õpattern space9Í2]Ab -e µ#½Epattern spaceÝscriptÝ ÆX|?¿ÍfÎb5Ý ×¡¼×ÅX|t;àÝ× PTÎ [address],[address]{ command[args] command[args] ... }
Tï
[address],[address]{command[args];command[args];...;command[args];}
N×command8 ybÍ-eÝ®àº.wÕ×Ípattern space | ¶W×Ísed script fileQ¡à-f Æ $ sed -f script_file file
TïNÍcommandÝt¡«wÍ5r; ¨²sedbÍhold spaceÎÍõD Ýbuffersedb°ú|¿à hold spacepattern space vi
« Ýyy dd wÕ×Í:Ý bufferàpú.¸§¼ u`Äò·®
ú
CHAPTER 4. SED
4.4
sed command
command
4.4.1
b25Íf´ðàÝ
4.4. SED COMMAND
39
ú
Ãͼ
µÎ.9¿Í_ìú.?¦ • Append a\ 0Õaddress¡appendXba\ ¡«XbC • Change c\ ;×ðZC • Delete d B*regex0ÕÝC£×BÎJB* • Insert i\ 0Õaddress¡3G«insertC • Substitution s/// ðÎtðàÝ • Translate y/// |×ÍC-×ÍC-®!Ýð a\ úi\ú¥a\ i\ KðáÝZCA ÝZC bðà\ 9ÍÐrîðAáÝZCb\ | à\\¼escape*\Ä9\bÝ®Þ ôµÎAZC
«!`b\ ’§ ð ãyshellÝSr ’ ^ð°^*9Í©ÿ¨¶scriptjX: » Ï× t¡×
cyril@gyoza:~$ cat last
Z: Ï× Z: t¡× Z:
cyril@gyoza:~$ sed ’a\ > > ’ last
Z: ¬vÆð°øÄ×::¢ §` øÄ×` º§ø §9øÝ®Þ
cyril@gyoza:~$ sed ’$a\ > > sed > ’ last sed: -e expression #1, char 93: Unterminated ‘s’ command
Z: ¬vÆð°øÄ×::¢ §` øÄ×`\ º§ø §9øÝ®Þ Ï× u`Äò·®
cyril@gyoza:~$ sed ’$a\ > > sed > ’ last
ú
4.4. SED COMMAND
CHAPTER 4. SED
t¡× Z: ¬vÆð°øÄ×::¢ §` øÄ×` sedº§ø §9øÝ®Þ ¬½»P×ð r
cyril@gyoza:~$ cat address.txt 270 <Michele’s Address>
¬½n ×ð10r
cyril@gyoza:~$ cat insert.sed //i\ 100 Gyoza Blvd\ San Jose, CA
¬½»P×ð r
cyril@gyoza:~$ sed -f inser.sed address.txt 270 <Michele’s Address> 100 Gyoza Blvd San Jose, CA
¬½n ×ð10r
9Íú«a\ i\ ©b×F¥ µÎA;ÝZC ¬9J adressÎÍrange 1,109ø`XbÝrangeKº´¬v© b×;Ý
c\ change
Ï× ÏÞ t¡×
cyril@gyoza:~$ cat last first line second line last line cyril@gyoza:~$ cat change.sed 1,2c\
Ï׫ÏÞK*Ý Ï׫ÏÞK*Ý t¡× last line
cyril@gyoza:~$ sed -f change.sed last
u`Äò·®
ú
CHAPTER 4. SED
4.4. SED COMMAND
41
¶¶ .Ï×ÕÏèݶ¶
$ sed ’1,10y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/’ lower.txt
ðÝúb¥ÝÏÞ· §A3×/ÝCÙ)ðÝb 9 Í£/ºàÏ×ÍÙ)Ýð*Að*©Ýµ3¡«î Ý Ï¿ÍIð*àg9Íflag Ï× ÏÞ t¡×
cyril@gyoza:~$ cat last first line second line last line
Ï× ÏÞ t¡×
cyril@gyoza:~$ sed ’s/first/line/1’ last line line second line last line
Ï× ÏÞ t¡×
cyril@gyoza:~$ sed ’s/first/line/2’ last first line second line last line
Ï× ÏÞ 9 t¡×
cyril@gyoza:~$ cat lines first line second line multiple line line last line
Ï× ÏÞ 9 t¡×
cyril@gyoza:~$ sed ’s/line/row/2’ lines first line second line multiple line row last line
Ï× ÏÞ 9 t¡×
cyril@gyoza:~$ sed ’s/line/row/g’ lines first row second row multiple row row last row
4.4.2
pattern/hold space
Ý §
ÝÎ# • h .hold space
Ýz*.pattern spaceÝcopyhold space u`Äò·® • l list pattern space
ú
4.4. SED COMMAND
CHAPTER 4. SED
.pattern spaceÝ3hold space¡« • g .pattern space
Ýz*.hold spaceJ/pattern space • G .hold spaceÝ3pattern space¡« • p pattern spaceÝ • x øð(exchange)pattern spacehold space l«pÝ-½3E&ASCIIÝ § • H
Ï× ÏÞ t¡×
cyril@gyoza:~$ cat last first line second line last line
Ï× Ï× ÏÞ ÏÞ t¡×
cyril@gyoza:~$ sed ’1,2p’ last first line first line second line second line last line cyril@gyoza:~$ sed ’1,2l’ last \262\304\244@\246\346 first line$ first line \262\304\244G\246\346 second line$ second line last line
Ï× ÏÞ t¡× 9\|Epattern spaceb?ÝÝÏ× Õpattern space :Õp.Ï× #½pattern spaceWoutputX|sedê. ×Å#½ÏÞ
¼Ý3pattern space
:Õp.ÏÞ !§êbËÍÏÞ Ïëãyp^®àà#Îpattern space XÕoutput:×Í»(' ¼Ý) cyril@gyoza:~$ cat command.txt This describes the Linux ls command. This describes the Linux cp command. cyril@gyoza:~$ cat command.sed /Linux/{ h s/.* Linux \(.*\) .*/\1:/ p x }
u`Äò·®
CHAPTER 4. SED
ú
4.4. SED COMMAND
43
cyril@gyoza:~$ sed -f command.sed command.txt ls: This describes the Linux ls command. cp: This describes the Linux cp command.
Tï¶W×
cyril@gyoza:~$ sed ’/Linux/{h;s/.* Linux \(.*\) .*/\1:/;p;x;}’ command.txt
9\:Ï×Íh.Ï×. hold spaceÄBpattern space1b æÍÏ ×ÝQ¡ð*Wls:¨3pattern space©bls: Q¡pls:t ¡.hold space«ls:øðX|t¡pattern space/ µÎæÍÝsed WoutputXcpÎ!øݼ§ X|^%©ÎËÍ¿:ÕÝspace3£\ð¼ð./39Ë Í 2]33copy/pasteµ?ÝA!viÝßT|º 4.4.3
×M
9 §]º 3æÍÝh, H, g, G, x
«K©bE× §Apattern match¬ `µRDì«Ýú༠§Ë|îÝpattern matchCpattern space, hold spaceÝ § • n .pattern spaceX\áì×X|ì×Wpattern space Ý • N \áì׫êGpattern spaceÝ =R¼×¬Î
«b ÍembeddedðÐr|à \n¼îB©b9`|à\n¼ î • D *ÕÏ×embedded newlineI N)à AD3t9ìÆ ÝJpattern space1ºì¼ ]ºÕscriptcм×g • P printÕbembedded newlineÝ×1ºXbpattern space A P3t9ìÆÝJpattern space1ºì¼ ]ºÕscriptc м×g JoinË /join/ { N s/\n/ /g }
.9èç*W×èç u`Äò·®
ú
4.4. SED COMMAND
CHAPTER 4. SED
/^$/ { N /^\n$/D }
:0Õèç¡.ì× ¼A©b×èçèç ì× ¿W×1º3pattern spaceÄ9`ìÍú /^\n$/D^®àpattern spaceIX AbËèçX|Delete*Ï×èçyì×èç 1ºì¼ 9`. Dú¨b®àÝX|¬Xpattern spaceÝ µ /^$/×àºb×èçºì¼9\DPKb]ºÝ®à |J¼ ®¥Ý § flow control branch
9Î༻ÉúÆݵ Îc
Ýif else, while9°×ú 9¤g:×R àã:'×ÍlabelQ¡àb label®Õ9Í2]Æ • : label, 'label • b label branch ðÕlabel2]ÆA^blabelµ;;Æ à#® Õscript O • t label A×ÍðWtest ?fWñ¡®Õlabel X|Ä6 s///ú×Ràsú×3túG 91A:» $ cat join.txt join second line C
3 +DEaCÝ; \ 9׫î×Î=3×sÝ $ sed ’{ :a N s/\\\n// t a}’ join.txt join second line C
3 +DEaCÝ; 9׫î×Î=3×sÝ 9j § • r \jn ÞjnappendÕêGpattern space • w ¶jn Þpattern spaceݶÕ×Íjn u`Äò·®
CHAPTER 4. SED $ cat insert.sed //i\ 100 Gyoza Blvd\ San Jose, CA
Ï× ÏÞ 9 t¡×
$ cat lines first line second line multiple line line last line
Ï×
$ sed ’/first/r insert.sed’ lines first line //i\ 100 Gyoza Blvd\ San Jose, CA second line multiple line line last lin
ÏÞ 9 t¡×
Ï× ÏÞ 9 t¡×
$ sed ’/first/w firstline.txt’ lines first line second line multiple line line last line
Ï×
$ cat firstline.txt first line
Í
r • q Òsed • =
Ï× ÏÞ 9 t¡×
$ cat lines first line second line multiple line line last line $ sed -e ’/first/=’ -e ’/second/q’ lines 1 first line second line
Ï× ÏÞ u`Äò·®
ú
4.4. SED COMMAND
45
ú
4.4. SED COMMAND
CHAPTER 4. SED
b9Ý»:http://www.student.northpark.edu/pemente/sed/sedfaq.html
u`Äò·®
Chapter 5
awk 5.1
+
ÝÌFÎawkfsed?àÝ2]8Eysed××Ý §awkèºÝ × /IûtÝ §b?powerfulÝ CP+°]º× § ;P |Î field
awk ’script’ var=value files awk -f scriptfile var=value files
ÍvarÎÝawkóvalueÎÝÂ9|༫shellóÚ; ¨² sedÝregular expressKJ×¼®/ÝíáfE9ø^ b ÄPawk.&àawkÝ×Íó¼®regular expressÝíáfE.h û ô |DêÝJ¼fExÎàfEÕÐ ¼«×Íregular expressfE var ~ /re/ var !~ /re/
9øµ]-Ýv9fEô!øºF/true, false| W×Ícondition tÝû §|²awkb?9?àÝfunction|ñ§¨²ôbÝif,while, forfunctionÝæ9°fsed«shell)¿ÝæêîÝ&9ôÎÞ ¼ perlÝÃÍÝà 5.2
script
Ã
×Íscriptã condition{procedure},condition{procedure},.....àW «sed 0Õ%f(patternI )%®(procedureI ) b×°/IÝ ó|Q&Æ'×°fcondition|Îpattern regular expressTØ ÍÐ)f9Í:ìºÕÐrfEÕÐ ÍbËÍ¥ Ý/ 47
5.3.
óû §
CHAPTER 5. AWK
condition, BEGIN«END×Íscript;ðÎ9ø BEGIN {xxx} /re/{xxx} END{xxx}
׶P×binit;װµ ßbßO`^âC×ø P@ôb §¡Ýroutine¼ §awk® ×ÍPlVÝscript+ èºÝ×ÍgeneralÝ@Ý § ÕÕb¿Íèç $ awk ’BEGIN{x=0} /^$/{x++} END{print x}’ scripts.tex
×'x=0¡BEGIN¡Ýµ3ÆQ¡N\× ¼AÎèç µ x++t¡\Õj x B3î«Ý»
awkÝó«cÎ×øÝôµÎ^bþÐrÝ9 \«shell perlscriptf´×ø 5.3
ó û §
«¥ÝËÍL • record µÎ××Ý£] • field ;ðãspaceTïtab"âÝ£]ûµÎfield :»¬¥shell command lineÝSrÔSr awk
$ cat /etc/mnttab /proc /proc proc fd /dev/fd fd mnttab /etc/mnttab swap /var/run swap /tmp tmpfs
dev=31c0000 1022606134 rw,suid,dev=32c0000 1022606198 mntfs dev=3380000 1022606209 tmpfs dev=1 1022606209 dev=2 1022606211
$ awk ’/swap/{print $2}’ /etc/mnttab /var/run /tmp $ awk Hello Hello Hello Hello Hello
’{print "Hello World"}’ /etc/mnttab World World World World World
×Þû ÎtabÞëû Îèç u`Äò·®
CHAPTER 5. AWK
5.3.
$ cat datafile 99 98 3.5 300 298 4.9 498 493 5.9 699 698 7.6 900 748 9.0 1200 703 9.6 1500 651 10.4 1698 627 10.8
B 9øÎ
ËÍûí
×Íû
input output $ awk ’{print $1 $2}’ datafile 9998 300298 498493 699698 900748 1200703 1500651 1698627
9øÎinputËÍûíoutputËÍû àprintíûã
9øÎinputËÍûíoutput×Íû $ awk ’{print $1 "," $2}’ datafile 99,98 300,298 498,493 699,698 900,748 1200,703 1500,651 1698,627
ôµÎ1print $1$2 yprint $1 $2 u`Äò·®
ó û §
49
5.3.
óû §
5.3.1
CHAPTER 5. AWK
/ó
tÝ C+°Ýóx,y,z....awkb×°/Ýó( ûîÝ/ ó ARGC ARGV ARGIND $0 $1....$n
: : : : :
ENVIRON ERRNO
: :
number of arguments on command line array containing the command line arguments
Jrecord ÏnÍû(field) ×Íassociate arrayâbIÝ(ó t¡systemýÝerror number:/usr/include/errno.h
FILENAME : FIELDWIDTHS :
current filename list of field widths
FS OFS RS ORS NF NR
field separator tab output field seperator record separator newline output record seperator newline number of field number of record
: : : : : :
/ÎèçT /Îèç /Î /Î
ÍFS, OFS, RS, ORS, NF, NRÎðàÕÝ:» $ cat /etc/passwd list:x:38:38:SmartList:/var/list:/bin/sh irc:x:39:39:ircd:/var:/bin/sh nobody:x:65534:65534:nobody:/home:/bin/sh cyril:x:1000:1000:Cyril Huang,,,:/home/cyril:/bin/bash $ awk ’{FS=":"; print $7}’ /etc/passwd /bin/sh /bin/sh /bin/sh /bin/bash $ awk ’{FS=":"; OFS=","; print $1,$6,$7}’ /etc/passwd list,/var/list,/bin/sh irc,/var,/bin/sh nobody,/home,/bin/sh cyril,/home/cyril,/bin/bash
u`Äò·®
CHAPTER 5. AWK
Ð~
5.3.
ó û §
51
|J¼®conditionà ô|J¼®conditionà¤góregular express matchÕ
NF NR $1 $2....
$ cat datafile # This is the data file from experiment 99 98 3.5 300 298 4.9 498 493 5.9 # Failed data 122 123 699 698 7.6 900 748 9.0 1200 703 9.6 1500 651 10.4 1698 627 10.8 $ awk ’NF == 3 && $1 ~ /[0-9]+/{print $3,$1,$2}’ datafile 3.5 99 98 4.9 300 298 5.9 498 493 7.6 699 698 9.0 900 748 9.6 1200 703 10.4 1500 651 10.8 1698 627
5.3.2
awk
óshelló
awk sedKÎQÃshell programmingÝ? Ì.h«shellóÚ; ; PÝ var=valuevarµÎawkóvalueµÎshellóÝÂ
# fs_mounted $dev $mnt_pt $fs_type # This is shell script version of fs_mounted, check if the file system is # mounted. fs_mounted() { _BINGO= [ $# -eq 3 ] || return $ERRNO_EINVAL _BINGO="‘$AWK ’{if (\$1 == _DEVICE && \$2 == _MNT_PT && \$3 == _FS_TYPE) print \$1}’ _DEV [ "$_BINGO" ] || return -1 return 0; }
u`Äò·®
5.3.
óû §
CHAPTER 5. AWK
shell scriptÝÆshell commandÝawkEy×°1ºC- §«sed×ø TF 9Í»
«¥$1 $2 $33AWK ’ ’Sr
«ÝÎawkÝ$1$2$3 3 ²« DEVICE=$1...ÎshellÝ $1 $2 $3 DEVICE MNT PT ÎawkÝ óX|awkÝ$1 $2 $3b\9Íescape3G«ôµÎ1shell §¸Æ¬. 9°Xawk §
5.3.3
pArraysplitÐó
XbawkÝarrayKÎassociate array,ôµÎhashôµÎñb(CidÝp 9Í(CidµÎhashÝkey×&Æà1, 2 ,3 ...¼ ®pÝidÛý3 awk
«.&&Æà(̼ id index¼¨´pÄawkÏA:Õ Îó ClÝindexô| 3C
«àÝ×ø ¥!parray[1]Îarray[0]«c×ø &Æ|¼ x[1], x[2]...Ýpï1,2,3 ...45 ¬associate arrayÝ4Î& Æ|×Ý¥associate arrayÝ¥ýà SrÀR¼:for loopÝà ° |àsplit(string, array, [sep])¼ÿÕ×Ípsep^bµàFSÝ 9ÍstringÝû5â×ÍûµÎ×Íp-ô $ cat split.awk #! /bin/awk BEGIN{FS=":"} /cyril/{ print $0 split($0, afield) for (i = 0; i < NF; ++i) { print i","afield[i] } delete afield[2] for (i = 0; i <= NF; ++i) { print i","afield[i] } } $ awk -f split.awk /etc/passwd lcyril:x:100:1::/export/lcyril:/usr/bin/bash 0, 1,lcyril 2,x 3,100 4,1 5,
u`Äò·®
CHAPTER 5. AWK
5.4.
ÃÍ×+°
53
6,/export/lcyril 7,/usr/bin/bash 0, 1,lcyril 2, 3,100 4,1 5, 6,/export/lcyril 7,/usr/bin/bash
ÃÍ×+°
5.4
tÝûÝó©à°²awkfsedúÝ3y?#P+Ý×] ° awkÝ+° c1@3awkËÝbcÝÃ|µºÝ Q ô|. awk.c 5.4.1 C
ó.ìÕÐ
Ý×ó.
9Îfortranݼó)
+ - * / % ++ -- ^ **( C
Ý×¼ = += -= *= /= %= ^= **=
C
Ý×ì Ý
! == < > <= >= != && || ?: (c cond ? result1 : result2
AcondWñ/result1Q/result2)
ÝìÕÐ
«bÍf´©½ÝµÎpattern matchÕÐ ~, !~ Þ ¼ bàÝv«ÕÐ~=xÎregular express;ðmatchÝÎ ×®
/ÝfEAEØÍ©óre match`µàÕ9ÍÕ Ð AxÎÍZ°óC condition perl
if (x ~ /^[0-9]+/) { x += y }
u`Äò·®
5.4.
ÃÍ×+°
5.4.2
CHAPTER 5. AWK
if
^%ÝRµÎc if (condition) { } else if (condition) { } else { }
¥else if«c+°×ø 5.4.3
for loop
9\ÝforbËÍÎcbourne shellÝá)perlôÎ×øÄperlàÝ c shellÝ+° for (i = 0; i < 10; i++) { } for x in xarray { }
:» $ cat gyoza.awk #! /bin/awk heehee BEGIN { x[1]="I" x[2]="am" x[3]="a" x[4]="gyoza" y["I"]="I" y["am"]="am" y["a"]="a" y["gyoza"]="gyoza" for (i = 1; i < 5; i++) { print x[i] } for item in x { print item, x[item] } for item in y { print item, y[item] } }
u`Äò·®
CHAPTER 5. AWK
¡«Ý
5.5. FUNCTION 55
^bঠ&©Îþ9ÍBEGIN
gyoza.awk $ awk -f gyoza.awk gyoza.awk I am a gyoza 2 am 3 a 4 gyoza 1 I gyoza gyoza am am I I a a
5.4.4
while
^%ÝRµÎc while (condition) { statment } do { statment } while (condition) for loopwhile loopK«c×ø|àbreakÒcontinue9loopðÕì Í loop
5.5
function
«cH×øÝ9Î×Ëscriptà#type
×ô^b% pass by value, pass by addressóÎglobalÝ # ;P function fun(arg1, arg2) { arg1 = arg2 xxxx }
4Ý»
$ cat sort.awk
u`Äò·®
5.6.
ÍÐó
CHAPTER 5. AWK
# sorting function function sort(Array, elements, temp, i,j) for (i = 2; i<= elements; ++i) { for(j = i; array[j - 1] > array[j]; --j) { temp = array[j] array[j] = array[j - 1] array[j - 1] = temp } } return } # main routine, { for (i = 2; i <= NF; ++i) { grades[i - 1] = $i } sort(grades, NF-1) printf("%s: ", $1) for (j = 1; j <= NF - 1; ++j) { printf("%d ", grades[j]) } printf("\n") }
××¼
YY
$ cat grade.txt 100 60 75 23 100 98 99 89
YY
$ awk -f sort.awk grade.txt : 23 60 75 100 : 89 98 99 100
ÍÐó
5.6 5.6.1
C §-matchð
Cî § sedbs///9Ëðÿàî×°/Ðó • F/Ð)regexÝ3stringÝH match(string, regex)
•
F/C: F/3ÏmÍC-?¡ónÍC-ÝCn^µÕ9 substr(string, m, [,n])
ð: ðÝ¿ÍÐóbÝF/©½ u`Äò·®
CHAPTER 5. AWK • •
.
«Ð)
5.6.
ÍÐó
57
ÝÏ×ÍCðWstring1WF/1
string2 regex sub(regex, string1, string2)
.string2
«Ð)regexÝCgloballyÝIðWstring1 ysedÝs///g F/Jóîðóê gsub(regex, string1, string2)
•
F/×ÍC string2
«Ð)regexÝÏnÍCðWstring1 ysedÝs///nth match ¬Îstring2^b; gensub(regex, string1, nth match, string2)
^;;Î$0nth match|àgTGîglobally(I):»
string2
$ cat match.awk #! /bin/awk BEGIN{FS=":"} /cyril/{ print $0 print match($0, /cyril/) print substr($0, match($0, /cyril/), length("cyril")) print gensub(/cyril/, "mark", 2) print $0 sub(/^.*cyril/, "mark") print $0 } $ awk -f match.awk /etc/passwd lcyril:x:100:1::/export/lcyril:/usr/bin/bash 2 cyril lcyril:x:100:1::/export/lmark:/usr/bin/bash lcyril:x:100:1::/export/lcyril:/usr/bin/bash mark:/usr/bin/bash
9Í»àÝlength()9ÍÐóregexàSrbstringÝ2]à double quoteÀR¼àgensubº;string2Ý v:ÏëÍprint $09\ ÎbgreedyÝ[T3X|©yì¡«×^ 5.6.2
íáí §print(f )
íî¼1printÎÝà°Äb??Ýformatíµ c
Ýprintf Tïfortran×ø printf()
à°«cÐó×ø
{printf("The sum on line %s is %d.\n", NR, $1+$2)}
u`Äò·®
5.6.
ÍÐó %s %d %n.mf
CHAPTER 5. AWK
î×ÍC î×ÍJó î×ÍnÍJómÍóÝFó
Bórand()
5.6.3
®ß+y0 Õ 1 ÝBó BEGIN { srand(systime()) random_num = rand() print random_num }
F/1970, 1, 1Õ¨3ÝJó srand()®ß×ÍÌaÝBóp|º ¸à
systime() rand()
5.6.4
Ùsystem()
9Í UnixÝsystem()9ÍÐó BEGIN {if (system("ls -l")) != 0) { print "command failed" } }
ÍÝ ó.Ðóµ|+ÛÝ
u`Äò·®
Chapter 6
perl 8Eysed, awk, shell script Ì Larry WallÆÿs×Ë|ã ×°ÓÚÓâscript½;àlÝscript ÌfRXbÝscriptpower §Rregular expressô?]-XÝ×°AgreedyÝ®Þperlt¡« system callÝ=jn,processsocket programÝ §¯WúÝ script+ perl«ÍÑshell, TCL/expect...script+Í@ÎàC¶¼Ý N ×ËscriptÍ@KÎ×ÍÆP©Ä9ÍÆPUÿ×°/+° ºÕ9°!JQ¡»ð9°scriptó×]ºW Ýcó« ]º Q¦!Í@t¡ÎKÎassemblyÝó«]º¼Æµ«shell, awk× ø
6.1
6.1.1
ÃÍ+°£]lV ó
Ñ'ãÂKÍþÐr 59
6.2.
?POWERÝREGULAR EXPRESSION
6.1.2
6.2 6.3 6.4 6.4.1
f×
?powerÝregular expression ðàÐó Ù § process
6.4.2
jn
6.4.3
system call
6.5
module
u`Äò·®
CHAPTER 6. PERL
Chapter 7
Bourne shell, perl
´
C+ ° f
9ÍÍ@Î&OSÝb`BàÝC, shell perlÎ&ðàÕÝ Ì ¨3E93Ë Ì+°Íf´ 7.1
ó
Ló shell var= perl $var =
C int var = char var = Makefile var = var :=
¸àó shell $var ${var} awk var
61
7.2.
pHASH
+°f´
CHAPTER 7. BOURNE SHELL, PERL C
perl $var C var Makefile ${var} or $(var)
¥ÝÎ • shellÝL$ ¬á¼óÂ`×$ perlµf´×l ÑA¢ µÎ$Ðr CµÎK • shellÝrG¡bèç var= var = Î×øÝ perlCµ^b§×MakefileÎL¸à «shell ×ø¬ÎrG¡|bèçX|b°Ë4B×ì 7.2
pHash
shell array="e1 e2 e3" perl @array = {e1, e2 ,e2}; %hash = {key1 => val1, key2 => val2, key3 => val3}; C int array[] = {1, 2, 3}; shell
Ýl£]§list
«-ôàspace5tðàÝ)
for var in $array do cmd1 done array
Ý-ôµÎàspace5Ý£] perlbÍ Ýforeach
foreach $var (@array) { xxx }
Í@9ÎC shellݶ° C^b 9ø×Í×Í;arrayÝ-ôóÝ^ × u`Äò·®
+°f´
CHAPTER 7. BOURNE SHELL, PERL C
7.3
fB
7.3.
fB
63
shell if test; then dosomething elif test; then doother else allright fi perl if (c) { do_something; } elsif () { do_other; } else { allright; } C if (c) { do_something; } else if () { do_other; } else { allright; }
9\¥ÝÎshellmÀrelse ifݶ°ëÍ×øfP¶° shell^b×à()fP©testÎØÍÆÝBµ? 7.3.1
ff´
shell
C [ "str1" = "str2" ] óÂ [ num1 -ne num2 ] perl
C if ($str1 ne $str2) óÂ if ($num1 == $num2)
u`Äò·®
7.4.
]º×
+°f´
CHAPTER 7. BOURNE SHELL, PERL C
C
C if (strcmp(str1, str2)) óÂ if (num1 == num2)
¥óÂf´Cf´C §ìf´ ã9\&Æ|:Í @perlÎ&ðbÄPúÝ 7.4 7.4.1
]º × while
]º
shell while test do cmd done perl
«cÎ×øÝtÝóà°×ø
while (condition) { statment1; } unless (condition) { statment1; } C while (condition) { statment1; } do { statment1; } while (condition)
7.4.2
for loop
Ý Î C
Ýfor loop
Bourne shell for
for var in "element1 element2 element3..." do echo $var done
u`Äò·®
+°f´
CHAPTER 7. BOURNE SHELL, PERL C perl
bËËforÝà°
for ($i = 0; $i < 10; $i++) { statement } foreach $var (@array) { statement; } C
Ýà°
for (i = 0, init = 1; i < 10; i++) { statement; }
7.5
P
shell func1() { arg1=$1 arg2=$2 } awk function func1(arg1, arg2) { xxx } perl sub func1(arg1, arg2) { xxx } C int func1(int arg1, char *arg2) { xxx }
u`Äò·®
7.5.
P
65
7.6.
7.6
Û
Û
shell # comment perl # comment C /* comment */
u`Äò·®
+°f´
CHAPTER 7. BOURNE SHELL, PERL C
Bibliography [1] Linux In a Nutshell, Ellen Siever, O’Reilly & Associates, ISBN 0596000251 [2] Sek & Awk, Dale Dougherty, et al, O’Reilly & Associates, ISBN 1565922255 [3] Perl Cookbook, Tom Christiansen, Nathan Torkington O’Reilly & Associate, ISBN 1565922433 [4] The C Programming Language, Brian W. Kernighan, Dennis M. Ritchie, Prentice Hall, ISBN 0131103628
67