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

Slides:



Advertisements
Similar presentations
CIS 240 Introduction to UNIX Instructor: Sue Sampson.
Advertisements

More Shell Programming Software Tools. Slide 2 Keyword Shell Variables l The shell sets keyword shell variables. You can use (and change) them. HOME The.
Introduction to Unix – CS 21 Lecture 11. Lecture Overview Shell Programming Variable Discussion Command line parameters Arithmetic Discussion Control.
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Shell Programming Software Tools. Slide 2 Shells l A shell can be used in one of two ways: n A command interpreter, used interactively n A programming.
CS 497C – Introduction to UNIX Lecture 33: - Shell Programming Chin-Chih Chang
Integer variables #!/bin/csh # sum of numbers from $argv[1] to $argv[2] set low = $argv[1] set high = $argv[2] set sum = 0 set current = $low while ( $current.
Shell Programming Learning Objectives: 1. To understand the some basic utilities of UNIX File 2. To compare UNIX shell and popular shell 3. To learn the.
Further Shell Scripting Michael Griffiths Corporate Information and Computing Services The University of Sheffield
Bash Shell Scripting 10 Second Guide Common environment variables PATH - Sets the search path for any executable command. Similar to the PATH variable.
Shell Script Examples.
Shell Control Structures CSE 2031 Fall August 2015.
Shell Programming, or Scripting Shirley Moore CPS 5401 Fall August 29,
Agenda Control Flow Statements Purpose test statement if / elif / else Statements for loops while vs. until statements case statement break vs. continue.
1 Operating Systems Lecture 3 Shell Scripts. 2 Shell Programming 1.Shell scripts must be marked as executable: chmod a+x myScript 2. Use # to start a.
1 Operating Systems Lecture 3 Shell Scripts. 2 Brief review of unix1.txt n Glob Construct (metacharacters) and other special characters F ?, *, [] F Ex.
8 Shell Programming Mauro Jaskelioff. Introduction Environment variables –How to use and assign them –Your PATH variable Introduction to shell programming.
Chapter 5 Bourne Shells Scripts By C. Shing ITEC Dept Radford University.
Bash shell programming Part II – Control statements Deniz Savas and Michael Griffiths November 2005 Corporate Information and Computing Services The University.
Introduction to Linux OS (IV) AUBG ICoSCIS Team Prof. Volin Karagiozov March, 09 – 10, 2013 SWU, Blagoevgrad.
Linux Operations and Administration
CMPSC 60: Week 6 Discussion Originally Created By: Jason Wither Updated and Modified By: Ryan Dixon University of California Santa Barbara.
UNIX Shell Script (1) Dr. Tran, Van Hoai Faculty of Computer Science and Engineering HCMC Uni. of Technology
CS465 - UNIX The Bourne Shell.
#!/bin/sh echo Hello World cat Firstshellscript.sh Firstshellscript.sh.
Shell Programming. Introducing UNIX Shells  Shell is also a programming language and provides various features like variables, branching, looping and.
1 System Administration Introduction to Scripting, Perl Session 3 – Sat 10 Nov 2007 References:  chapter 1, The Unix Programming Environment, Kernighan.
CSC 352– Unix Programming, Spring 2015 March 2015 Shell Programming (Highlights only)
1 © 2001 John Urrutia. All rights reserved. Chapter 10 using the Bourne Again Shell.
Shell Programming. Creating Shell Scripts: Some Basic Principles A script name is arbitrary. Choose names that make it easy to quickly identify file function.
Chapter 10: BASH Shell Scripting Fun with fi. In this chapter … Control structures File descriptors Variables.
(A Very Short) Introduction to Shell Scripts CSCI N321 – System and Network Administration Copyright © 2000, 2003 by Scott Orr and the Trustees of Indiana.
Shell Programming Learning Objectives: 1. To understand the some basic utilities of UNIX File 2. To compare UNIX shell and popular shell 3. To learn the.
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
CIT 140: Introduction to ITSlide #1 CIT 140: Introduction to IT Shell Programming.
Xuan Guo Chapter 5 The Bourne Shell Graham Glass and King Ables, UNIX for Programmers and Users, Third Edition, Pearson Prentice Hall, Notes by Michael.
1 Lecture 9 Shell Programming – Command substitution Regular expressions and grep Use of exit, for loop and expr commands COP 3353 Introduction to UNIX.
1 © 2000 John Urrutia. All rights reserved. Session 5 The Bourne Shell.
CSCI 330 UNIX and Network Programming Unit IX: Shell Scripts.
Shell Programming Features “Full” programming language “Full” programming language Conditional statements Conditional statements Arithmetic, String, File,
Agenda Positional Parameters / Continued... Command Substitution Bourne Shell / Bash Shell / Korn Shell Mathematical Expressions Bourne Shell / Bash Shell.
1 Unix/Linux commands and shell programming-Part 2 (Dr. Mohamed El Bachir Menai)
More Shell Programming. Slide 2 Control Flow  The shell allows several control flow statements:  if  while  for.
Agenda The Bourne Shell – Part II Special Characters Ambiguous File Reference Variable Names and Values User Created Variables Read-only Variables (Positional.
UNIX Shell Script (2) Dr. Tran, Van Hoai Faculty of Computer Science and Engineering HCMC Uni. of Technology
Flow Control. The order in which commands execute in a shell script is called the flow of the script. When you change the commands that execute based.
Introduction to Bash Shell. What is Shell? The shell is a command interpreter. It is the layer between the operating system kernel and the user.
Shell script – part 2 CS 302. Special shell variable $0.. $9  Positional parameters or command line arguments  For example, a script myscript take 2.
If condition1 then statements elif condition2 more statements […] else even more statements fi.
Group, group, group One after the other: cmd1 ; cmd2 One or both: cmd1 && cmd2 Only one of them: cmd1 || cmd2 Cuddling (there):( cmd1 ; cmd2 ) Cuddling.
Compunet Corporation Introduction to Unix (CA263) Round and Round By Tariq Ibn Aziz Dammam Community College.
CS 403: Programming Languages Lecture 20 Fall 2003 Department of Computer Science University of Alabama Joel Jones.
1 Lecture 7 Introduction to Shell Scripts COP 3353 Introduction to UNIX.
By Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
1 UNIX Operating Systems II Part 2: Shell Scripting Instructor: Stan Isaacs.
Shell Control Structures CSE 2031 Fall June 2016.
1 Lecture 8 Shell Programming – Control Constructs COP 3353 Introduction to UNIX.
Shell Control Structures
CSC 352– Unix Programming, Spring 2016, Final Exam Guide
Agenda Bash Shell Scripting – Part II Logic statements Loop statements
Lecture 9 Shell Programming – Command substitution
Shell Programming (ch 10)
Agenda Control Flow Statements Purpose test statement
What is Bash Shell Scripting?
Shell Control Structures
Shell Control Structures
Chapter 5 Bourne Shells Scripts
More Shell Programming
Introduction to Bash Programming, part 3
Review The Unix Shells Graham Glass and King Ables,
Presentation transcript:

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

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

Variables and Backquotes cname="Computer Programming Class" gsnum=70 echo $cname: “#” of good students = $gsnum Computer Programming Class: # of good students = 70 … (same as above) bsnum=10 stnum=$gsnum+$bsnum echo $cname: total "#" of students = $stnum Computer Programming Class: total # of students = … (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 Stored as a String

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

Quoting Examples of Quoting Rules person=hatter ExpressionValue $personhatter "$person" [or] ""$person"" [or] ''$person ''hatter \$person$person '$person'$person "'$person'" [or] \'$person\''hatter' \"$person\" [or] "\"$person\"" [or] \""$person"\""hatter" \''$person'\''$person' '"$person"'"$person"

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 = $* martini:~$ arg.sh st command-line argument = $1 2nd command-line argument = 2 3rd argument = 3 # of arguments = 3 Entire list of arguments = Result

테스트 연산자 옵션의미기능 () 연산의 순서를 제어, 그룹핑 ! 부정 (NOT) 논리 연산자 -a 논리곱 (AND) -o 논리합 (OR) -z string string 의 길이가 "0" 이면 참 문자열 연산 -n string string 의 길이가 "0" 아니면 참 string1 = string2 string1 과 string2 가 같으면 참 string1 !=string2 string1 과 string2 가 같지 않으면 참 n1 -eq n2 두수가 같으면 참 숫자 연산자 n1 -ne n2 두수가 같지 않으면 참 n1 -gt n2 n1 이 크면 참 n1 -ge n2 n1 이 크거나 같으면 참 n1 -lt n2 n1 이 작으면 참 n1 -le n2 n1 이 작거나 같으면 참 -r file file 이 존재하고 읽을 수 있으면 참 파일 연산자 -w file file 이 존재하고 기록 가능하면 참 -x file file 이 존재하고 실행 가능하면 참 -f file file 이 존재하고 정규 파일이면 참 -d file file 이 존재하고 디렉토리이면 참 -s file file 이 존재하고 비어있지 않으면 참

Conditional Execution 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 martini:~$ cond.sh is less than 2 martini:~$ cond.sh is greater than 1 martini:~$ cond.sh equals to 1 Result Space

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 martini:~$backup.sh srcdir dstdir Execution

Quoting 보충 Examples of Quoting Rules person=hatter ExpressionValue $personhatter "$person" [or] ""$person"" [or] ''$person ''hatter \$person$person '$person'$person "'$person'" [or] \'$person\''hatter' \"$person\" [or] "\"$person\"" [or] \""$person"\""hatter" \''$person'\''$person' '"$person"'"$person"

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

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

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

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

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:~$

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

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

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

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 for i in do for j in do if ! [ -e./OUTPUT/output.$i.$j ]; then./pow $i $j >>./OUTPUT/output.$i.$j fi done martini:~$powsim.sh –b –c Execution

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 martini:~$ var_naming.sh Result To show the value 1, this ‘a’ should be ~, #, %, ^, *, -, +, =, {, [, }, ], :, \,,., ?, /, or [space]

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 martini:~$ echo ~# ~#  Some Exceptions a=1 echo $aa --- To show the value 1, the latter ‘a’ should be ~, #, %, ^, *, -, +, =, {, [, }, ], :, \,,., ?, /, or [space] ~echo ~; echo ~/ echo ~+ echo ~: echo ~ \ /home/net001 /home/net001/ /home/net001/Program (Current Directory) /home/net001: Continue on next line / Next character quote #echo /*., (part starting with # not shown because of the preceding space) *echo *~aaa~ (Wildcard if there is a match, aaa~) e.g., ~~

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