korn shell programming1 aix ver. 4 korn shell programming

44
Korn Shell Programming 1 AIX Ver. 4 Korn Shell Programming

Upload: gwendoline-mcdowell

Post on 12-Jan-2016

235 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 1

AIX Ver. 4

Korn Shell Programming

Page 2: Korn Shell Programming1 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

Page 3: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 3

CH1. Basic Shell Concepts

Page 4: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 4

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 사용

Application

Shell

Kernel

H/W

UNIX System 에서 Shell 의 위치

CH1. Basic Shell Concepts

Page 5: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

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

Page 6: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 6

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

CH1. Basic Shell Concepts

Page 7: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 7

Korn Shell Configuration Files

Invoking the Korn Shell sources …(ksh 이 실행될때 . 소스가 불러오는 파일들은 다음과 같다 .)

/etc/environment ( 모든 AIX Process 의 환경이 설정된 파일 )

/etc/profile (Login 쉘의 환경이 설정된 파일 )

HOME/.profile ( 각 사용자별로 환경이 설정된 파일 )

ENV 파일 (Korn Shell 의 환경변수는 ENV 파일에 List 화 )

CH1. Basic Shell Concepts

time

ENV(Environment Variable) Value Changes 현재 자신에게 설정된 “환경변수” 확인 … set [ 참고 ] Shell 에 따라서 output 형태가 조금씩 다름 .

이번 작업 (현재 ,login 상태 )에서만 기본 프린터를 바꾸는 경우 … Ex> setenv PRINTER=ps2

환경변수를 지정하고 그것을 로그인해있을동안 유효하게 할 경우 … EDITOR=vi [ 참고 ] Export 란 ? 부모가 자식 process 에게 모든 변수를 물려 줌 export EDITOR

// 위와 같은 경우 , 다음 쉘이 실행되야 그 값을 적용 및 사용 가능한데 , 그렇게 하지않고 , 바로 그 값을 사용하려면 … source .profile

Page 8: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 8

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> * ? ! [ ] [ - ]

CH1. Basic Shell Concepts

Page 9: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 9

CH1. Basic Shell Concepts

Process I/O

Input ProcessOutput

Error

(0)(1)

(2)

Command Line Editing and Recall[ESC] 키 (Editing Mode 로 변경 ) :

h 커서를 좌측으로 이동

l 커서를 우측으로 이동

k ( 또는 -) 이전 command 로 이동 (.sh_history 파일로 부터 읽어들임 )

j ( 또는 +) 현재 command 다음 command 로 이동

[참고 ] Ctrl + m … 현재 Line 실행 / … 특정 command 찾기

Page 10: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 10

CH2. Variables

Page 11: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

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

[ 참고 ] { } 생략시 , 그 변수와 변수 다음 문자열은 인식못함 .

Page 12: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 12

CH2. Variables

Positional Parameters$1 to $9

[ 참고 ] 1부터 9 까지 그냥 No. 만 지정해주고 , 그 다음 (즉 . 9 이상으로 변수를 선언 ) 부터는 { }를 붙여…

${1} to ${9}

# 단 . ‘Korn Shell’ 에 한해서 임 .

Setting Positional ParametersEx> vi test print $1 $2 $3 set a b print $1 $2 $3

[참고 ] 즉 . 변수에 해당하는 “값 (=Positional Parameters)”을 받아 수행

Page 13: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

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 the First Field Separator (the default is a space) Ex> “$*” = “$1 $2 $3 . . .”

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

Some Shell Parameters

Page 14: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 14

CH3. Return Codes and Traps

Page 15: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 15

CH3. Return Codes and Traps

Return Values$? 방금 전 실행코드를 return

[ 참고 ] zero(0) … “Standard Output” ( 즉 . 정상출력 ) non-zero(0 외의 수 )… “Error” occurred

# 단 . ‘Korn Shell’ 에 한해서 임 .

Exit Statusprint $$ … 현재 , 쉘의 PID(Process ID) 확인

ksh … 새로운 Sub 쉘 시작

print $$ … 위 바뀐 Sub 쉘의 PID 확인

exit … 바뀐 sub 쉘의 종료 (원래 , 쉘로 돌아감 .)

print $? … return code 로 방금전 실행코드의 오류 여부를 확인

Page 16: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 16

CH3. Return Codes and Traps

Conditional ExecutionA 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 ’ 를 뜻함 .

Page 17: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 17

CH3. Return Codes and Traps

Compound ExpressionsFor 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

Page 18: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 18

CH3. Return Codes and Traps

Signals

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 ’ 로 남김

Signals sent to processes may be

Caught

Ignored

Defaulted

Page 19: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

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

Page 20: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 20

CH4. Flow Control

Page 21: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 21

CH4. Flow Control

The if - the – else Construct[ “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

[ Example ]

If [[ $# -ne 1 ]]then print “Usage is: Example If “ exit 1fi

Page 22: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 22

CH4. Flow Control

Conditional Loop Syntax[ “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

[ Example ]

until cc prog.cdo vi prog.cdone

Page 23: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

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

Page 24: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 24

CH4. Flow Control

[ “case” Syntax ]

case word in (pattern1 | pattern2 | …) action ;; (*) default ;; esac

----------------------------------

case $identifier in (pattern1) cmd1 more_cmds ;;(pattern2 | pattern3) cmds ;;(*) cmds ;; esac

[ 참고 ] 샘플 스크립트 “ 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

Conditional Syntax

Page 25: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 25

CH4. Flow Control

[ “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

[ 참고 ] 샘플 스크립트 “ 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

Conditional Syntax

# 그외 , exit The Loop / break The Loop / continue The Loop 등이 있음 .

Page 26: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 26

CH5. Shell Commands

Page 27: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 27

CH5. Shell Commands

[ 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 ;; ……….

The getopts Command‘ getopts ’ 명령 … 매개변수 리스트에서 인자값은 프로세서 옵션과 결합됨

Page 28: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

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 쉘의 옵션과 셋팅 된 값을 리스트해서 보여줌 .

Page 29: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

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) : 디버깅 옵션

Page 30: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 30

CH5. Shell Commands

Shell builtin CommandsWe have seen the following builtin Shell commands:

. : bg break

cd continue echo eval

exec exit export fc

fg getopts jobs kill

print pwd read readonly

set shift test [ ]

trap typeset unset wait

In the later units we will see:

alias command let or (()) return

times ulimit unalias whence

[ 참고 ] 모든 ‘ builtin cmd’ 는 현재 환경변수 (environment) 에 수행될 수 있다 .

Page 31: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 31

CH6. Korn Shell Types, Commands & Shell Functions

Page 32: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 32

CH6. Korn Shell Types, Commands & Functions

Defining Functions

command 는 그룹과 함께 이름지어 질수 있음 .command 의 설정은 Funtion 의 Body 를 구성함 .Funtion 정의는 ... 아래와 같다 .

Bourne Korn Identifier () function identifier

{ {

commands commands

} }

Page 33: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

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

}

Page 34: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

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” 에 넣어주면 됨

Page 35: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

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

Page 36: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 36

CH7. Regular Expressions & Text Selection

Page 37: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

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 allowed egrep allows multiple (either|or) patterns

Page 38: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 38

CH7. Regular Expressions & Text Selection

grep ExamplesEx1> $ 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

Page 39: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 39

CH8. Utilities for Personal Productivity

Page 40: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 40

CH8. Utilities for Personal Productivity

sed

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 !

Stream editor

Requestededits

0 1

Standard input Standard ouput

Page 41: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 41

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”

CH8. Utilities for Personal Productivity

Page 42: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 42

The Substitute InstructionThis 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

CH8. Utilities for Personal Productivity

Page 43: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 43

The crontab CommandThis 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

CH8. Utilities for Personal Productivity

crontab ExamplesHere 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 {} \;

Page 44: Korn Shell Programming1 AIX Ver. 4 Korn Shell Programming

Korn Shell Programming 44

crontab File FormatCron 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)

CH8. Utilities for Personal Productivity