150 likes | 290 Views
Lecture 17: Shell Programming ( ch 10). IT244 - Introduction to Linux / Unix Instructor: Bo Sheng. Control Structure. select select varname [in arg … ] do commands done Example ~it244/it244/lec17/select1. Control Structure. select select varname [in arg … ] do commands
E N D
Lecture 17: Shell Programming (ch 10) IT244 - Introduction to Linux / Unix Instructor: Bo Sheng
Control Structure • select select varname [in arg …] do commands done • Example ~it244/it244/lec17/select1
Control Structure • select select varname [in arg …] do commands done • PS3: select prompt • Terminate: exit, break • Example: ~it244/it244/lec17/select2
Parameters and Variables • Special parameters • $#: number of arguments • $1-$n: arguments • $0: name of the script • Example: ~it244/it244/lec17/abc • ./abc • ~it244/it244/lec17/abc • basename: ~it244/it244/lec17/abc2 • basename ~it244/it244/lec17/abc
Parameters and Variables • Special parameters • $$: PID number • echo $$ • ps • Example: ~it244/it244/lec17/id2 • ./id2 • echo $$
Parameters and Variables • Special parameters • $?: exit status • ls; echo $? • ls xyz; echo $? • cat yyy; echo $? • Example: ~it244/it244/lec17/es • ./es • echo $? • echo $?
Parameters and Variables • Initialize command-line arguments • set arg1 arg2 … • ~it244/it244/lec17/set_it • date • ~it244/it244/lec17/dateset
Some More Examples • Get file sizes • ~/it244/it244/lec17/filesize $ls -l -rwxr-xr-x 1 it244 libuuid 50 2010-11-04 00:09 abc -rwxr-xr-x 1 it244 libuuid 62 2010-11-04 00:10 abc2 -rwxr-xr-x 1 it244 libuuid 79 2010-11-04 00:49 bb1 -rwxr-xr-x 1 it244 libuuid 79 2010-11-04 00:49 bb2 … … … for i in * do set -- $(ls -l "$i") echo $i: $5 bytes done
Some More Examples • Length of a string • VAR=hello • echo ${#VAR} • Find the longest filename • ~it244/it244/lec17/longest • . longest • maxfn • maxfn ~/it244
File Descriptors • An index number of a open file • 3 system file descriptors • 0(std input), 1(std output), 2(std err) • Create a file descriptor • exec n > outfile • exec m < infile • exec n<>file • exec n>>outfile
File Descriptors • Duplicate a file descriptor • exec n<&m • exec n>&m • Close a file descriptor • exec n<&- • Example: ~it244/it244/lec17/exec_read ~it244/it244/lec17/exec_write
File Descriptors • Example with a function • Execute a script in the current shell • . fun_mycp • source fun_mycp • ~it244/it244/lec17/fun_mycp
Control Flow • The order of executing commands • if..then..else • Read arguments • Example ( shift ) ~it244/it244/lec15/shift2args • Example ( $@ ) ~it244/it244/lec15/allargs
Control Flow • The order of executing commands • if..then..else • Optional arguments • Example ~it244/it244/lec15/out
Parameters and Variables • Array • name=(element1 element2 …) • NAMES=(max helensamzach) • echo ${NAMES[2]} • * and @ • A=(“${NAMES[*]}”) • B=(“${NAMES[@]}”) • declare -a • Number of elements: echo ${#NAMES[*]}