1 / 24

Computer Programming Batch & Shell Programming 9 th Lecture

Computer Programming Batch & Shell Programming 9 th Lecture. 김현철 컴퓨터공학부 서울대학교 2009 년 가을학기. Slide Credits. 엄현상 교수님 서울대학교 컴퓨터공학부 Computer Programming, 2007 봄학기. 순서. Bash Shell Programming Quoting 보충 Looping Per-Case Execution Array Example Miscellaneous Q&A.

bryant
Download Presentation

Computer Programming Batch & Shell Programming 9 th Lecture

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Computer ProgrammingBatch & Shell Programming 9th Lecture 김현철 컴퓨터공학부 서울대학교 2009년 가을학기

  2. Slide Credits • 엄현상 교수님 • 서울대학교 컴퓨터공학부 • Computer Programming, 2007 봄학기

  3. 순서 • Bash Shell Programming • Quoting 보충 • Looping • Per-Case Execution • Array • Example • Miscellaneous • Q&A

  4. Bourne Shell Scripts #!/bin/sh # Generate some info date echo $HOME echo $USER echo $PATH cal • Result 2007. 04. 03. (화) 11:52:37 KST /csehome/net001 net001 /usr/local/bin:/usr/bin:/bin … (omitted)

  5. Variables and Backquotes cname="Computer Programming Class" gsnum=70 echo $cname: “#” of good students = $gsnum Stored as a String Computer Programming Class: # of good students = 70 … (same as above) bsnum=10 stnum=$gsnum+$bsnum echo $cname: total "#" of students = $stnum Stored as a String Computer Programming Class: total # of students = 70+10 … (same as above except for the last two lines) stnum=`expr $gsnum`+ $bsnum` echo $cname: total "#" of students = $stnum Computer Programming Class: total # of students = 80

  6. Quoting : Rules 1) Single Quotes(')따옴표로 둘러 쌓여 기술된 모든 특수문자들은 쉘로부터의 번역이모두 금지된다. 따옴표는 특수문자의 기능을 필요에 의해 제한하기위해서 사용한다. 2) Double Quotes(“)쌍 따옴표는 따옴표와 동일한 기능을 수행한다. 단, $, `, \의 3가지특수문자는 영향을 받지않고 정상대로 쉘에의해 번역된다. 3) Backquotes (`)역 따옴표에 기술되어 있는 문자열을 쉘에게 실행 명령어라는 것을알려주기 위해 사용한다. 쉘은 이 명령어를 실행한후 생성된 출력을명령어가 지정된 위치에 위치시킨다.( 주의 ) 이상 3가지의 보호문자는 반드시 쌍으로 이루어 진다.만일 쌍으로 지정되지 않은 경우에는 문법 에러를 발생한다. 4) Backslash(\)역 슬래쉬는 연이어 기술된 다음 한자가 갖고 있는 특수문자의처리를 쉘이 수행하지 못하도록 처리한다.

  7. Quoting • Examples of Quoting Rules person=hatter

  8. Command-Line Arguments echo '1st command-line argument = $1' echo "2nd command-line argument = $2" echo 3rd argument = $3 echo "# of arguments = $#" echo Entire list of arguments = $* • Result martini:~$ arg.sh 1 2 3 1st command-line argument = $1 2nd command-line argument = 2 3rd argument = 3 # of arguments = 3 Entire list of arguments = 1 2 3

  9. 테스트 연산자

  10. Conditional Execution Space if [ $1 –lt $2 ]; then echo $1 is less than $2 elif [ $1 –gt $2 ]; then echo $1 is greater than $2 else echo $1 equals to $2 fi Space • Result martini:~$ cond.sh 1 2 1 is less than 2 martini:~$ cond.sh 2 1 2 is greater than 1 martini:~$ cond.sh 1 1 1 equals to 1

  11. Bourne Shell Script Example if [ -z $1 ] || [ -z $2 ]; then echo usage: $0 source_dir target_dir else SRC_DIR=$1 DST_DIR=$2 OF=output.`date +%y%m%d`.tar.gz if [ -d $DST_DIR ]; then tar -cvzf $DST_DIR/$OF $SRC_DIR else mkdir $DST_DIR tar -cvzf $DST_DIR/$OF $SRC_DIR fi fi • Execution martini:~$backup.sh srcdir dstdir

  12. Quoting 보충 • Examples of Quoting Rules person=hatter

  13. Shell 특수변수 • ┌────┰─────────────────────────────┐│ 변수   ┃ 목적                                                      │├────╂─────────────────────────────┤│ $0     ┃명령어 라인상의 명령어 이름이 설정                        │├────╂─────────────────────────────┤│ $#      ┃명령어 라인상에 기술되어 있는 인자의 갯수가 설정           │├────╂─────────────────────────────┤│ $*     ┃명령어 라인내의 전체 인자가 설정                           │├────╂─────────────────────────────┤│ "$@"    ┃$*와 같다. 그러나따옴표로 둘러쌓인 인자를 하나의 인자로   ││         ┃처리하는 것이 $*와 틀린 점이다.                            │├────╂─────────────────────────────┤│ $$      ┃현재의 프로세스 식별자(PID)가 설정                        │├────╂─────────────────────────────┤│ $!      ┃Background에서 직전에 실행됐던 프로세스의 식별자가 설정   │├────╂─────────────────────────────┤│ $?      ┃직전에 Foreground에서 실행됐던 명령어의 종료상태가설정    │├────╂─────────────────────────────┤│ $-      ┃현재 설정된 쉘 옵션이 설정                                 │

  14. Looping Double Quotes around $@ for arg in "$@"; do # correct echo $arg done for arg in "$*"; do # wrong echo $arg done • Result martini:~$ loop.sh 1 "2 2" 3 1 2 2 3 1 2 2 3

  15. Looping (계속) martini:~$ ls backup.C backup.c backup1.C backup1.c martini:~$ more for.sh for cfilename in *$1*u?.[cC]; do echo $cfilename done • Results martini:~$ for.sh a backup.C backup.c martini:~$ for.sh c backup.C backup.c

  16. Looping (계속) let i=i+1 # bash only i=0 while [ $i –lt 3 ]; do echo $i i=`expr $i + 1` done` • Result martini:~$ while.sh 0 1 2

  17. Per-Case Execution echo Enter your command \(who, list, or quit \) while read command; do case $command in who) who; echo Done with running who;; list) ls; echo Done with running ls;; quit) break;; *) echo Enter who, list, or quit;; esac done • Result martini:~$ case.sh Enter your command (who, list, or quit) who net001 pts/2 Mar 31 13:26 … (omitted) Done with running who list … Done with running ls date Enter who, list, or quit quit martini:~$

  18. Array (bash Only) • Variable Containing Multiple Values • No Maximum Limit to the Size • No Requirements That Member Variables Be Indexed or Assigned Contiguously • Zero-Based

  19. Array (계속) a1=(one two three) echo ${a1[*]} echo a1[*] echo ${a1[@]} echo a1[@] echo ${a1[0]} echo a1[0] echo ${a1[3]} unset a1[3] unset a1[*] echo ${a1[0]} # unset i=0 echo $i unset i echo $i ------- 0 • Result one two three a1[*] one two three a1[@] one a1[0]

  20. Bash Script Example (계속) i=0 status=0 if [ $# -lt 1 ]; then echo Usage: $0 [-b base1 base2...] [-c expo1 expo2...] exit 1 fi for arg in "$@"; do if [ -n "`echo $arg | grep '-'`" ]; then if [ $arg = -b ]; then status=1 elif [ $arg = -c ]; then status=2 fi else case $status in 1 ) base[$i]=$arg; i=`expr $i + 1` ;; 2 ) exponent[$i]=$arg; i=`expr $i + 1` ;; * ) echo Usage: $0 [-b base1 base2...] [-c expo1 expo2...]; exit 1 ;; esac fi done # to be continued on the next slide

  21. Bash Script Example (계속) if ! [ -d OUTPUT ]; then mkdir OUTPUT if [ $? -gt 0 ]; then # if the exit status of the previous command indicates a failure echo Remove/Rename the OUTPUT File exit 1 fi fi for i in ${base[@]}; do for j in ${exponent[@]}; do if ! [ -e ./OUTPUT/output.$i.$j ]; then ./pow $i $j >> ./OUTPUT/output.$i.$j fi done done • Execution martini:~$powsim.sh –b 3 4 5 –c 12 14 16

  22. Shell Programming 보충 • Bash Variable Naming • letter -> A | B | … | Z | a | b | … | z • digit -> 0 | 1 | … | 9 • u_s -> _ • var_name -> (letter | u_s)(letter | digit | u_s)* a=1 echo $aa To show the value 1, this ‘a’ should be ~, !, @, #, %, ^, *, -, +, =, {, [, }, ], :, \,, ., ?, /, or [space] • Result martini:~$ var_naming.sh

  23. Shell Programming 보충 (계속) • Character Echoing • Shown as Expected If There Is Space Before and After the Character (Refer to Handout 7) • Possibly Shown Verbatim If There Is an Adjacent Character e.g., ~~ a=1 echo $aa --- To show the value 1, the latter ‘a’ should be ~, !, @, #, %, ^, *, -, +, =, {, [, }, ], :, \,, ., ?, /, or [space] martini:~$ echo ~# ~# • Some Exceptions

  24. Miscellaneous • Stream Editor: sed • Global Search and Replace • Character Translator: tr • Regular Expressions • for Editors (Including sed) and grep • Option Interpretation: getopts • Functions • Signals • …

More Related