1 / 44

AIX Ver. 4 Korn Shell Programming

AIX Ver. 4 Korn Shell Programming. 목 차. CH1. 기본 Shell 개념 CH2. 변수 CH3. Return Codes 와 Traps CH4. Flow 제어 CH5. Shell 명령 CH6. Fuctions 와 Commands CH7. Text Selection Utilities CH8. Utilities for Personal Productivity. CH1. Basic Shell Concepts. Application. Shell. Kernel.

lanza
Download Presentation

AIX Ver. 4 Korn Shell Programming

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. AIX Ver. 4 Korn Shell Programming Korn Shell Programming

  2. 목 차 CH1. 기본 Shell 개념 CH2. 변수 CH3. Return Codes와 Traps CH4. Flow 제어 CH5. Shell 명령 CH6. Fuctions와 Commands CH7. Text Selection Utilities CH8. Utilities for Personal Productivity Korn Shell Programming

  3. CH1. Basic Shell Concepts Korn Shell Programming

  4. Application Shell Kernel H/W CH1. Basic Shell Concepts Shells ‘Shell’이란? - 사용자(Application)와 Kerner간의 ‘인터페이스’ 역할 • 명령어 해석기(Command Interpreter) 역활 Shell의 종류 • Bourne (sh) • 최초의 Shell로Bell 연구소에서 Stephen Bourne이 개발 • 명령어 해석기 역할 및 Shell program 개발환경 제공 • C (csh) • University of California Berkeley에서 개발 • 명령어 Stack을 이용한 History 기능, Alias 기능 제공 • Korn (ksh) • Bourne Shell + C Shell의 기능을 추가 • [참고] Aix경우. Default shell … ksh 사용 UNIX System에서 Shell의 위치 Korn Shell Programming

  5. CH1. Basic Shell Concepts • 자신이 사용하는 현재, 쉘 알아보기 … echo $SHELL [참고] /usr/bin/ksh (‘ksh’즉. Korn Shell을 뜻함) /.../sh Bourne shell /.../csh C shell /.../tcsh TC shell /.../ksh Korn shell /.../bash Bourne Again SHell • 현재 시스템에서 사용할 수 있는 쉘이 어떤 것이 있는지 알아 보기 … vi /etc/shells [참고] 각 쉘이 제공하는 기능들 Bourne C TC Korn BASH --------------------------------------------------명령 히스토리 No Yes Yes Yes Yes명령의 별명 No Yes Yes Yes Yes쉘 스크립트 Yes Yes Yes Yes Yes파일이름 완성하기 No Yes* Yes Yes* Yes명령행 편집 No No Yes Yes* Yes job 제어 No Yes Yes Yes Yes -------------------------------------------------- • 작업중에 다른 쉘로 바꾸기 … csh (변경하고자 하는 쉘명) (즉. 현재 자신의 login상태를 유지하면서 그 login쉘의 하위 PS로 또 하나의 쉘을 실행) [참고] login중에 (다시 접속하는 과정없이) 바로 로그인 쉘 변경 … exec csh –l • login 쉘 바꾸기(change shell) … chsh Korn Shell Programming

  6. CH1. Basic Shell Concepts Shell Script ‘Shell Script’란? - Text file에 저장된 명령어의 집합 • 시스템command / 쉘 command / 변수지정 / 제어문법 등으로 Program 됨 Shells실행하기 • ksh (사용하고자하는 쉘명) • exec ksh [참고] exec 명령 … shell ‘builtin command’ (즉. 내장 명령어) Script실행하기 • . prog(특정 스크립트 명) … Script가 현재 shell environment에서 수행됨 • ksh(특정 쉘 명) prog(특정 스크립트 명) …특정 쉘로 스크립트를 실행 [참고] Script file은 … Read permission 필요 ksh invokes a script in a subshell Korn Shell Programming

  7. CH1. Basic Shell Concepts Korn Shell Configuration Files Invoking the Korn Shell sources …(ksh이 실행될때. 소스가 불러오는 파일들은 다음과 같다.) /etc/environment (모든 AIX Process의 환경이 설정된 파일) /etc/profile (Login쉘의 환경이 설정된 파일) HOME/.profile (각 사용자별로 환경이 설정된 파일) ENV 파일 (Korn Shell의 환경변수는 ENV파일에 List화) time ENV(Environment Variable) Value Changes • 현재 자신에게 설정된 “환경변수” 확인 … set [참고] Shell에 따라서 output 형태가 조금씩 다름. • 이번 작업(현재,login상태)에서만 기본 프린터를 바꾸는 경우 … Ex> setenv PRINTER=ps2 • 환경변수를 지정하고 그것을 로그인해있을동안 유효하게 할 경우 … EDITOR=vi [참고] Export란 ? 부모가 자식 process에게 모든 변수를 물려 줌 export EDITOR // 위와 같은 경우, 다음 쉘이 실행되야 그 값을 적용 및 사용 가능한데, 그렇게 하지않고, 바로 그 값을 사용하려면 … source .profile Korn Shell Programming

  8. CH1. Basic Shell Concepts Metacharacters Metacharacter란? ‘Shell이 특별한 의미로 해석하는 문자들’로 다음과 같이 3가지 유형이 있음[참고] command가 실행되기전에, 쉘이 먼저 처리(processing)함. Metacharacters끼리 함께(Mix) 사용 하는것도 가능. ① Wildcards metacharacters - ‘‘(Single quotes) … Quotes 사이의 모든 Metacharacter를 무시- “”(Double quotes) … $ ` \ 을 제외한 모든 Metacharacter를 무시Ex> find / -name “a*”–print …“”를 붙여주지 않을경우, 쉘이 먼저 처리(해석) 함. - \(Backslash) …특별한 의미를 가지는 Metacharacter를 무시 ② Korn Shell metacharacters Ex> * ? > < / ; & ! [ ] | $ \ ‘“ ③ Quoting Metacharacters파일 패턴을 찾거나 Matching 시키는데 사용되는 metacharacter문자의 일종. Ex> * ? ! [ ] [ - ] Korn Shell Programming

  9. CH1. Basic Shell Concepts Process I/O (1) Output (0) Input Process (2) Error Command Line Editing and Recall [ESC]키 (Editing Mode로 변경) : h 커서를 좌측으로 이동 l 커서를 우측으로 이동 k (또는 -) 이전 command로 이동 (.sh_history 파일로 부터 읽어들임) j (또는 +) 현재 command 다음 command로 이동 [참고] Ctrl + m …현재 Line 실행/ …특정 command 찾기 Korn Shell Programming

  10. CH2. Variables Korn Shell Programming

  11. CH2. Variables Setting Variables [syntex] variable name = value Ex> var1=Fri [참고] 변수선언 시 ‘읽기 권한’만 부여함으로써, 그 변수값에 대해 변경 여부의 제한을 둘 수 있음 readonly variable name = value 또는 typeset –r Variable Name = value Referencing Variables [syntex] Print $var1 Ex> varl=Mon print Today is ${varl}day [참고] { } 생략시, 그 변수와 변수 다음 문자열은 인식못함. Korn Shell Programming

  12. CH2. Variables Positional Parameters $1 to $9 [참고] 1부터 9까지 그냥 No.만 지정해주고,그 다음(즉. 9 이상으로 변수를 선언)부터는 { }를 붙여… ${1} to ${9} # 단. ‘Korn Shell’에 한해서 임. Setting Positional Parameters Ex> vi test print $1 $2 $3 set a b print $1 $2 $3 [참고] 즉. 변수에 해당하는 “값(=Positional Parameters)”을 받아 수행 Korn Shell Programming

  13. CH2. Variables Variable Parameters $# The number of Positional Parameters set Ex> print "$# Today is Monday" $@ Positional Parameters in a space separated list Ex> “$@” = “$1””$2””$3” . . . $* Positional Parameters in a list separated by theFirst Field Separator (the default is a space) Ex> “$*” = “$1 $2 $3 . . .” Some Shell Parameters Shell Parameters that remain fixed for the duration of the Script: $0 The (path)name used to invoke the Shell Script $$ The PID(Process ID) of current process (shell) $- Shell Options used to invoke the Shell, e.g. -r Parameters set as the Script executes command: $! The PID of the last background process $? The return code from the last command executed Korn Shell Programming

  14. CH3. Return Codes and Traps Korn Shell Programming

  15. CH3. Return Codes and Traps Return Values $?방금 전 실행코드를 return [참고] zero(0) …“Standard Output” (즉. 정상출력) non-zero(0 외의 수)…“Error” occurred # 단. ‘Korn Shell’에 한해서 임. Exit Status print $$ …현재, 쉘의 PID(Process ID) 확인 ksh …새로운 Sub 쉘 시작 print $$ …위 바뀐 Sub 쉘의 PID 확인 exit …바뀐 sub 쉘의 종료 (원래, 쉘로 돌아감.) print $? … return code로 방금전 실행코드의 오류 여부를 확인 Korn Shell Programming

  16. CH3. Return Codes and Traps Conditional Execution A return code (or exit status) can be used to detemine whether ornot to execute the next command (즉. ‘축약된 If문’이라고 보면 됨) command1 && command2 …좌측 cmd1이 참이면, 우측 cmd2를 실행 Ex> rm –f file1 && print file1 removed command1 || command2 …좌측 cmd1이 거짓이면, 우측 cmd2를 실행 Ex> who|grep kys1 || print kys1 logged off The test Command # 조건문에서 String 또는 File 비교할 때 많이 쓰임 test expression or [[ expression ]] [참고] return 값이, ‘ 0 ’이면 … expression 이 ‘true ’를return 값이, ‘ 0 ’이 아니면 … expression 이 ‘false ’를 뜻함. Korn Shell Programming

  17. CH3. Return Codes and Traps Compound Expressions For the [] or test command exp1 -a exp2 … and 연산자exp1 -o exp2 … or 연산자! Exp not 연산자\( \) grouping For the [[ ]] syntax exp1 && exp2 …둘다(both) 모두 참일때exp1 || exp2 …둘중 하나만(either) 참일때! Exp not 연산자() grouping File test Operators -s file … size-r file … readable ( -w file … writable )-x file … executable ( -e file … exits )-f file … ordinary ( -d file … directory )-u file … SUID bit set ( -g file … SGID bit set )-b file … block special ( -c file … character special )-L file … symbolic link Korn Shell Programming

  18. CH3. Return Codes and Traps Signals Signals sent to processes may be • Caught • Ignored • Defaulted Signal List 0 EXIT 과정 또는 기능이 완료할 때 실행 (특별한 쉘의 경우)1 HUP 로그인 되어있는 동안 수행 (서브 쉘에서 수행) 2 INT interrupt (Ctrl + c 중단)3 QUIT interrupt등의 신호를 exit (ctrl + \) 15 TERM default kill 명령18 TSTP suspend (ctrl + z 정지) [참고] 위 신호(signal)들은 kill명령(command) 다음에 오는 옵션으로 사용 되어지며, 18 TSTP 신호로 정지 시킨 것을 다시 수행할려면, ‘0’신호(exit)을 사용하면 됨.그외 3 QUIT 신호의 경우 …‘ core dump ’로 남김 Korn Shell Programming

  19. CH3. Return Codes and Traps Catching Signals with Traps ‘ trap ’명령 …프로세서가 신호를 받을 때 특별한 프로세서의 작용을 함 • To process signals • trap ‘rm /tmp/$$; print signal!; exit 2’ 2 3 • To ignore signals • trap ‘’ INT QUIT • To reset signal prcessing • trap – INT QUIT ( 즉. 2 interrupt 와 3 quit 신호로 … trap 2 3 으로도 사용가능) • To list traps set • trap Korn Shell Programming

  20. CH4. Flow Control Korn Shell Programming

  21. CH4. Flow Control The if - the – else Construct [ Example ] If [[ $# -ne 1 ]]then print “Usage is: Example If “ exit 1fi [ “If” Syntax ] If exp1then cmd to be executed if exp1 is trueelif exp2then cmd to be executed if exp1 is false, and exp2 is trueelif exp3then cmd to be executed if exp1 and exp2 Are false, but exp3 is trueelse cmd to be executed if all exps are false fi Korn Shell Programming

  22. CH4. Flow Control Conditional Loop Syntax [ Example ] until cc prog.cdo vi prog.cdone [ “until” Syntax ] until expdo cmd executed when exp is falsedone # optional < file [ Example ] until cc prog.cdo vi prog.cdone [ “while” Syntax ] while expdo cmd executed when exp is falsedone # optional < file Korn Shell Programming

  23. CH4. Flow Control Conditional Syntax [ “for” Syntax ] for identifier in word1 word2 …do cmd using $identifier more cmdsdone ------------------------------------------- for identifier # equivalent to: for identifier in “$@”do cmd using $identifier which takes values from the positional parametersdone [ Example ] for file in *.tmpdo rm –f $filedone [참고] 샘플 스크립트 “test_for” #!/usr/bin/ksh # test_for - select price from "pricelist" file # for each item entered on the command line # Usage: getprice item1 item2 ... # for item do grep -i "$item" pricelist done Korn Shell Programming

  24. CH4. Flow Control Conditional Syntax [참고] 샘플 스크립트 “test_case” #!/usr/bin/ksh # Usage: match string # To see how lucky you are feeling today case "$1" in Ace ) print "Ace !" ;; King ) print "King !" ;; Queen ) print "Queen !" ;; Jack ) print "Jack !" ;; * ) print "* ?" ;; esac [ “case” Syntax ] case word in (pattern1 | pattern2 | …) action ;;(*) default ;;esac ---------------------------------- case $identifier in (pattern1) cmd1 more_cmds ;;(pattern2 | pattern3) cmds ;;(*) cmds ;; esac Korn Shell Programming

  25. CH4. Flow Control Conditional Syntax [참고] 샘플 스크립트 “test_select” #!/usr/bin/ksh # Usage: test_select ps3="Pick an animal: " select animal in cow pig dog quit do case $animal in (cow) print "Moo !" ;; (pig) print "Oink !" ;; (dog) print "Woof !" ;; (exit) print "exit !" ;; ('') print "Not in the select !" ;; esac done [ “select” Syntax ] select identifier in word1 word2 …do cmds using $identifier usually containing a case statement done ---------------------------------- select identifier # equivalent to: select identifier in ”$@”do cmds using $identifier from positional parameters usually containing a case statement done # 그외, exit The Loop / break The Loop / continue The Loop 등이 있음. Korn Shell Programming

  26. CH5. Shell Commands Korn Shell Programming

  27. CH5. Shell Commands The getopts Command ‘ getopts ’명령 …매개변수 리스트에서 인자값은 프로세서 옵션과 결합됨 [ Syntax ]getopts optionstring variable parameter … [참고] 샘플 스크립트 “test_ getopts” #!/usr/bin/ksh # Example of getopts USAGE="Usage: example.test_getopts [+-c] [+-v] [-a arhument]" while getopts :a:cv arguments do case $arguments in a) arguments=$OPTARG ;; c) compile=on ;; ………. Korn Shell Programming

  28. CH5. Shell Commands The set Command "set" 명령에의해 실행되는 3개의 기능을 보면 다음과 같다 • set … set 변수에 대한 값을 리스트화 함. • set value …해당 매개변수 값에 대해 re – sets 을 함. • set –o vi … korn쉘의 라인에 명령어들의 리콜과 편집기능을 가능하게 함 • 이 마지막 명령어들은 “korn쉘" 옵션에 의해 설정됨.(단. 몇몇의 옵션은 설정은 다음과 같다) • set –o (또는 set -L) cmd …해당 옵션 기능 on • set +o (또는 set +L) cmd …해당 옵션 기능 off • [참고] set -o … korn쉘의 옵션과 셋팅 된 값을 리스트해서 보여줌. Korn Shell Programming

  29. CH5. Shell Commands Shell Options With Set • a (allexport) : 각각의 변수 설정을 자동으로 export 함 • (bgnice) : bg 즉. 백그라운드 작업의 우선권은 낮게 설정함 • C (noclobber) : 리다이렉션 연산자로 파일에 덥어쓰기 함 • b (notify) : 백그라운드 작업이 끝나면 notify • s : 매개변수 값에 대해 정렬 • v (verbose) : 화면의 입력에 대해 standart error로 읽어들임 • vi : history line recall and vi editting • x (xtrace) : 디버깅 옵션 Korn Shell Programming

  30. CH5. Shell Commands Shell builtin Commands We have seen the following builtin Shell commands: . : bgbreak cdcontinueechoeval execexitexportfc fggetoptsjobskill printpwdreadreadonly setshifttest[ ] traptypesetunsetwait In the later units we will see: aliascommandletor (()) return timesulimitunalias whence [참고] 모든 ‘builtin cmd’는 현재 환경변수(environment)에 수행될 수 있다. Korn Shell Programming

  31. CH6. Korn Shell Types, Commands & Shell Functions Korn Shell Programming

  32. CH6. Korn Shell Types, Commands & Functions Defining Functions command는 그룹과 함께 이름지어 질수 있음.command 의 설정은 Funtion의 Body를 구성함.Funtion 정의는 ... 아래와 같다. BourneKorn Identifier () function identifier { { commands commands } } Korn Shell Programming

  33. CH6. Korn Shell Types, Commands & Functions Function Examples [참고] 샘플 스크립트 “test_function” # Handy for usage errors in Shell Scripts # Invoke function usage with arguments: script # followed by arglist. Note exit status ! function usage { prog="$1"; shift print -u2 "$prog: usage: $prog $@" exit 1 } Korn Shell Programming

  34. CH6. Korn Shell Types, Commands & Functions Aliases The Korn Shell alias facility provides (즉. Command의 사용을 용이하게 해줌) • a way of creating new commands • a means of renaming existing commands Creation alias name=definition # name … alias명으로 사용할 명령어definition …‘원래 존재하는 명령어’Ex> alias ll='ls -l‘ Deletion unalias name Ex> unalias ll [참고] alias 를 매번 “Loging”시 마다 사용하고자 하는 경우. 해당 사용자(user)의 홈 디렉토리에 존재하는 “.profile”에 넣어주면 됨 Korn Shell Programming

  35. CH6. Korn Shell Types, Commands & Functions alias Examples $ alias-x ls=‘ls -a’ls is set and exported $ x=10 $ alias px=“print $x” rx=‘print $x’ $ x=100 $ px prints $x as it was 10 $ rx prints the latest $x 100 $ alias od=done an alias for some flow control $ for I in lazzy done > do > Print $1 > od Lazy done Korn Shell Programming

  36. CH7. Regular Expressions & Text Selection Korn Shell Programming

  37. CH7. Regular Expressions & Text Selection grep Command • Search file(s) or standard input for lines containing a match for a specific pattern • grep [options] pattern [ file1 file2 . . . ] • Vaild grep metacharacters: . * ^ $ [-] • . any single character * zero or more occurrences of the preceding charater ^a any line that begins with “a” ^$ any line that ends with “z” [a-f] any ONE of the characters in the stated range • Valid options: • -c print only a count of matching lines -i ignore the case of letters when making comparisons -l print only the names of the files with matching lines -n number the matching lines -s works silently, displays only error messages -v print lines that do NOT match -w do a whole word search • # There are other greps in the family: • fgrep only fixed string allowedegrep allows multiple (either|or) patterns Korn Shell Programming

  38. CH7. Regular Expressions & Text Selection grep Examples Ex1> $ grep -i “tech support” phone.list Ex2> $ grep bob /etc/passwd Ex1> $ ps -ef | grep tracy Ex1> $ ls -l | grep ‘^d’ Ex1> $ grep -n ‘.*’ /etc/passwd > \ > passwd.file.numbered.lines Ex1> $ egrep ‘^b(I|o)’ /etc/passwd Korn Shell Programming

  39. CH8. Utilities for Personal Productivity Korn Shell Programming

  40. CH8. Utilities for Personal Productivity sed Stream editor 1 0 Requestededits Standard input Standard ouput There are several ways of running sed: • sed‘edit-instructions’ filename • command | sed‘edit-instructions’ • sed–f command.file filename • # The input file is not changed or overwritten by sed ! Korn Shell Programming

  41. CH8. Utilities for Personal Productivity Line Selection The sed instructions operate on all lines of the input, unless you specify a SELECTION of lines:sed ‘SELECTION edit-instructions’ SELECTION can be • a single line number 1 = line 1 of the input $ = line list line of the input • a range line number 5, $ = from line 5 to the end of the input • a regular expression to select lines matching a pattern /string/ = selects all lines containing “string” • a range using regular expressions /^on/,/off$/ = from the first line beginning with “on” to the first ending in “off” Korn Shell Programming

  42. CH8. Utilities for Personal Productivity The Substitute Instruction This Instruction changes data Syntax: s/old string/new string/g 1. To replace the first occurrence of “Smith” on each line with “Smythe” sed ‘s/smith/smythe/’ phone.list 2. To replace all occurrences of “Smith” with “Smythe” using a different dellmiter sed ‘s!smith!smythe!’ phone.list 3. To replace each phone number with “Tel:” sed ‘/[0-9]\{3\}-[0-9]\{4\}/s/Tel: &/g’ \ phone.list Korn Shell Programming

  43. CH8. Utilities for Personal Productivity The crontab Command This command is like at but for regular “jobs” Syntax: crontab [-e : -l | -r] [job_file] The commands excuted are in job-file (or from stdin)The options allow you to edit, list or remove your crontab file System administrator determines who may use cron Cron will mail the output of the command to crontab owner crontab Examples Here are some possible crontab file entries/lines # Run command at 0900 and 1200 Mon-Fri15 9,12 * * 1-5 /home/sa/games_off# Do some backups at 0200 Tue-Sat0 2 * * 2,3,4,5,6 /home/sa/backup daily # What does this one do?13 5 * * 0 fine $HOME –name ,\* -exec rm –f {} \; Korn Shell Programming

  44. CH8. Utilities for Personal Productivity crontab File Format Cron needs crontab files in a paarticular formatEach line has time(s) and the command to run Format of each line is a set of fields • minute (0-59) • hour (0-23) • day (1-31) • month (1-12) • day of week (0-6, 0=Sunday) • Each of the first five fields may be • a number • a comma separated number list (1,3,4,13) • a range (4-9) • an asterisk (*) • # Sixth field contains the command(s) executed (a % means a newline) Korn Shell Programming

More Related