숙명여대 창병모 2011 가을 1. 2 a command processor that's run in a text window allows...

60
숙숙숙숙 숙숙숙 2011 숙숙 1

Upload: cuthbert-curtis-booker

Post on 03-Jan-2016

221 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

숙명여대 창병모2011 가을

1

Page 2: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

2

Page 3: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

A command processor that's run in a text window allows the user to type commands which cause actions, can also read commands from a file, called a script.

It supports filename wildcarding, piping, here documents, command substitution, variables and control structures for conditions and iteration

Its interactive features and overall C style made it easier and faster to use.

http://www-cs.canisius.edu/ONLINESTUFF/UNIX/shellprogramming.html

3

Page 4: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

4

Page 5: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

변수 여러 변수 설정 및 접근 방법

프로그래밍 언어 조건 분기 , 루프 , 인터럽트 처리

Aliasing 이명을 사용한 맞춤형 명령어

History 역사 (history) 메커니즘

고급 작업 제어 (advanced job control)

5

Page 6: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

#!/bin/sh if [ $days -gt 365 ] then

echo This is over a year.fi

#!/bin/csh if ( $days > 365 ) then

echo This is over a year. endif

6

Page 7: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

#!/bin/sh i=2 j=1 while [ $j -le 10 ]; do

echo '2 **' $j = $i i=`expr $i '*' 2` j=`expr $j + 1`

done

#!/bin/csh set i = 2 set j = 1 while ( $j <= 10 )

echo '2 **' $j = $i @ i *= 2 @ j++

end

7

Page 8: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

C 쉘의 시작 과정 login shell

로그인할 때 생성된 csh shell

손수 생성된 csh

8

Step Shell type Action1 both Execute commands in

$HOME/.cshrc2 login shell Execute commands in

"/etc/login"3 login shell Execute commands in

$HOME/.login

Page 9: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

.login 파일 환경 변수 설정

echo -n “Enter your terminal type:”set termtype=$<set term=vt100if (“$termtype” != “ “)

set term=“$termtype$”set path=(. /bin /usr/bin /usr/local/bin)stty erase “^?” kill “^U” intr “^C” eof “^D”set history = 40set prompt = “! %”

.cshrc 파일 이명 설정 등 개인적인 설정

9

Page 10: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

10

Page 11: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

11

Page 12: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

단순 변수 생성 및 배정

% set {name [= word]}*

단순 변수 접근

12

Syntax Action$name the value of name.${name} the value of name.${?name} 1 if name is set, and

0 otherwise

Page 13: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

%set flag%echo $flag%set color=red%set name=“Graham Glass”%echo $name

%set… display all local variables

%set verb=sing%echo I like $verbing%echo I like ${verb}ing

13

Page 14: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

리스트 변수 생성 및 배정% set {name = ( {word}* ) }*

% set colors = (red yellow blue)

리스트 변수 접근

리스트 구성 리스트 끝에 새로운 원소 추가 : (list element)

14

Syntax Action$name[selector]${name[selector]}

the element of namewhose index isspecified by selector

$#name${#name}

the number ofelements in name

Page 15: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

%set colors=(red yellow green)%echo $colors[1]%echo $colors[2-3]%echo $#colors

%set colors[4]=blue%set colors = ($colors blue)%echo $colors%set colors = $colors black%echo $colors

%set girls=(sally georgia)%set boys=(harry blair)%set both=($girls $boys)

15

Page 16: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

사전 정의 지역 변수 (Predefined local variables)

16

Name Value$< the next line of standard input, fully quoted$argv a list that contains all of the positional

paramenters: $argv[1] = $1.$cwd the current working directory$history the size of the history list$home the shell's home directory$$,$n,$* Command line arguments$prompt the shell prompt$shell the full pathname of the login shell$term the terminal type$path a list of directories to be searched for$verbose set if the -v command line option is used

Page 17: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

# grep -i unix $1

# foreach i ($*)grep -i unix $i

end

17

Page 18: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

환경 변수 생성 및 배정% setenv name word

사전 정의 환경 변수 (Predefined environment variable)

18

Name Value$USER $user$TERM $term$PATH $path$PWD $cwd$TERMCAP terminal's characteristic$LD_LIBRARY_PATH library paths used by ld$LOGNAME the shell owner's user id

Page 19: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

#echo -n “do you like the C shell ?”set reply = $<if ($reply == “yes”) thenecho you entered yes

else if ($reply =~ y*) thenecho I assume you mean yes

endif

19

Page 20: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

20

String

Operator

Meaning

== true if the string operands are equal

!= true if the string operands are unequal

=~ Like ==, except that the operand may

contain wildcards

!~ Like !=, except that the operand may contain

wildcards

Page 21: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

21

Arithmetic

Operator

Meaning

- unary minus

! logical negation

* / % multiplication, division, remainder

+ - addition, subtraction

<< >> bitwise left shift, bitwise right shift

<= >= < > relational operators

== != equality, inequality

|| && logical or, logical and

& ^ | bitwise and, bitwise xor, bitwise or

Page 22: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

22

%set a =2*2%@ a = 2 * 2%echo $a

%@ a = $a + $a%echo $a

%set flag = 1%@ b = ($a && $flag)%echo $b

#echo -n “enter the name of file …”set filename = $<if (! (-w “$filename”)) then ...

Page 23: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

23

Assigning the result of an expression to a variable

you cannot use the set command

the built in @ command

Command Meaning

@ list all the shell variables

@ variable = expr set variable to expression

@ variable[index]=expr set indexth element of

variable to expression

Page 24: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

// C groups from the left // prints 4 int i = 10 / 5 * 2;printf( "%d\n", i ); // prints 5 i = 7 - 4 + 2; printf( "%d\n", i ); // prints 16i = 2 >> 1 << 4;printf( "%d\n", i );

# C shell groups from the right # prints 1@ i = 10 / 5 * 2 echo $i # prints 1 @ i = 7 - 4 + 2 echo $i # prints 0 @ i = ( 2 >> 1 << 4 ) echo $i

24

Page 25: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

File-oriented expressions -e file file merely exists -r file file exists and is readable by user -w file file is writable by user -x file file is executable by user -o file file is owned by user -z file file has size 0 -f file file is an ordinary file -d file file is a directory

Boolean operators ! -- negate && -- logical and || -- logical or

25

Page 26: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

if (! -e somefile) then # does not exist

if (-f somefile && -w somefile) then # the file exists, is not a directory and I can write it

if (-e somefile) then grep $1 somefile

else echo "Grievous error! Database file does not exist".

endif

26

Page 27: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

27

명령어

alias [word [string]]

unalias pattern

유용한 것

alias ls ls -Falias rm rm -ialias rm ‘mv \!* ~/tomb’alias h historyalias ls-l ls -lalias mroe more

Page 28: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

28

이명 공유 서브쉘에서도 이용 가능하기 위해서는 이명

정의를 ".cshrc” 에 두어야 한다 .

매개변수를 이용한 이명 역사 메커니즘을 이용하여 이미 이명된

명령어의 인자를 사용할 수 있다 .

alias cd 'cd \!*; set prompt= "$cwd \!>" '

Page 29: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

29

Page 30: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

30

프로그래밍 언어처럼 만들기 위해 C Shell script CGI programming in Internet

#foreach color (red yellow green blue)echo one color is $color

end

Page 31: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

31

foreach

Repeat commandList, each time using a different

value in wordList for a named variable

foreach name (wordList) commandList end

goto

goto name .... name :

Page 32: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

32

if.csh

#echo -n ‘enter a number: ‘set number = $<if ($number < 0) thenecho negative

else if ($number ==0) thenecho zero

elseecho positive

endif

Page 33: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

33

if .. then ... else ... endif

if (expr) command

if (expr1) then list1else if (expr2) then list2else list3endif

Page 34: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

34

repeat

execute a single command a specified number of time

repeat expr command

% repeat 10 echo hi there

Page 35: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

35

menu.csh#!/bin/cshecho menu test programset stop = 0while ($stop == 0)

cat << ENDOFMENU1 : print the date2,3 : print the cwd4 : exit

ENDOFMENUecho -n ‘your choice ?’ ‘set reply = $<

switch ($reply)case “1” :

datebreaksw

case “2”:case “3”:

pwdbreaksw

case “4”: set stop = 1breaksw

default: echo illegal

choicebreaksw

endswend

Page 36: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

36

switch ... case ... endsw

switch (expr) case pattern1: list breaksw case pattern2: case pattern3: list2 breaksw default: defaultList endsw

Page 37: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

while … end

while (expr)commandList

end

37

Page 38: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

38

multi.csh#set x = 1while ($x <= $1)

set y = 1while ($y <= $1)

@ v = $x * $yecho -n $v ““@ y++

endecho “ “@ x++

end

%multi.csh 71 2 3 4 5 6 72 4 6 8 10 12 143 6 9 . . .

Page 39: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

39

junk -lp {fileName}*

기능파일을 지우는 대신에 홈 디렉토리 밑에 “ .junk” 라는 하위디렉토리에 옮긴다 . “.junk” 가 없으면 자동으로 생성한다 .

옵션-l option : “.junk” 의 현재 상태를 리스트한다 .-p option : “.junk” 휴지통 비우기

Page 40: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

40

#! /bin/cshset fileList = ( ) set listFlag = 0set purgeFlag= 0set junk = ~/.junkforeach arg ($*)

switch ($arg)case “-p” :

set purgeFlag = 1breaksw

case “-l” :set listFlag = 1breaksw

case -* :echo $arg is an illegal optiongoto errorbreaksw

default:set fileFlag = 1set fileList = ($fileList $arg)breaksw

endswend

Page 41: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

41

@ total = $listFlag + $purgeFlag +$fileFlagif ($total !=1) goto errorif (! (-e $junk)) then

‘mkdir’ $junkendifif ($listFlag) then

‘ls’ -lgF $junkexit 0

endifif ($purgeFlag) then

‘rm’ $junk/*exit 0

endifif ($fileFlag) then

‘mv’ $fileList $junkexit 0

endifexit 0error: ...

Page 42: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

#count number of files and directories in argument 1

#or current directory#usage: numfiles [directory]

if ($#argv == 0) thenset dir = “.”

else set dir = $argv[1]endif

if (! -d $dir) thenecho $0\: $dir not a directoryexit 1

endif

42

Page 43: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

echo $dir\:@ fcount = 0@ dcount = 0cd $dirforeach file (*)if (-f $file) then

@ fcount++else if (-d $file) then

@ dcount++endif

endecho $fcount files $dcount dirs

43

Page 44: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

44

Page 45: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

스크립트 없이 터미널에서 while 혹은 foreach 가능

%foreach f (*)? if (-d $f) echo $f? end

%set i = 2%set j = 1%while ($j <= 10)? echo ‘2 **’ $j = $i? @ i *= 2? @ j++? end

45

Page 46: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

onintr label인터럽트가 발생하면 해당 레이블로 제어 이전

#onintr controlCwhile (1)echo infinite loopsleep2

endcontrolC:echo control-C detected

46

Page 47: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

% headers

# Recursive script to print the head of each file # in the current directory and in every subdirectories

foreach i (*) if (-f $i) then

echo "========== $i ==========="

head $i endif if (-d $i) then

(cd $i; echo direcory $i; ~/lecture/sp/sample/headers) endif

end

47

Page 48: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

csh -vx script [arguments]

% csh -v menu.csh% csh -x menu.csh% csh -vx menu.csh

48

Page 49: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

재발명하지 말라 . Unix 명령어로 해결할 수 있는 작업은 C 프로그램보다 C 스크립트로 작성하라 . 텍스트 줄을 처리하는 작업 grep, sort, awk, 등 이용

왜 스크립트를 사용하는가 생성하고 유지하기 쉽다 . 디버깅도 쉽다 .

49

Page 50: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

스크립트을 위한 틀 리디렉션과 파이프 사용을 허용하라 인자의 수와 형태를 검사하라 파일과 디렉토리가 있는지 검사하라 적당한 오류 메시지를 내라 .

50

Page 51: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

프로세스 생성 C 쉘은 외부 명령어를 실행하기 위해 새로운 프로세스를 생성한다 .

따라서 foreach f (`ls`) 보다는 foreach f (*) 을 사용하는 것이 좋다 .

경로명 탐색 긴 경로명은 부담이 될 수 있다 .

cd $dir foreach file ($dir/*)foreach file (*) … … end

end

51

Page 52: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

52

Page 53: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

A shortcut for command re-execution

The { } metacharacters

Filename substitution

Redirection

Built-in

53

Page 54: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

54

명령어 숫자 붙이기 % set prompt='\! %' ... \! means the event number

명령어 기억 크기% set history = 40% set savehist = 32% history

역사 읽기history [-rh] [number]

Page 55: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

55

command re-execution

Form Action

!! the text of the last command

!number the text of the command with the

specfied event number

!prefix the text of the last command started

with prefix

!?substring the text of the last command that

contained substring

Page 56: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

A shortcut Re-execute the previous command with a slight modification

^pat1^pat2%cc fil.txt%^fil^file

Metacharacter { }a{b,c}d meansabd acd

%cp /usr/include/{stdio,signal}.h /tmp

56

Page 57: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

파일 이름 대치 무효화 $noglob 변수 set

%echo a* p*%set noglob%echo a* p*

매치되지 않는 상황 $nonomatch 변수 set

%echo a* p*%echo a* b*

echo: No match.%set nonomatch%echo a* b*

57

Page 58: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

Redirect stdout %cc a.c > errors

Redirect stdout & stderr%cc a.c >& errors

Redirect only stderr%(cc a.c > out) >& errors

Protecting file overwrite%ls -l errors%set noclobber%cc a.c >& errorserrors: File exists

58

Page 59: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

Pipe stdout command1 | command2

%cc a.c| more

Pipe stdout & stderr command1 |& command2 %cc a.c |& more

Pipe only stderr (process1>file) |& process2

%(cc a.c > out) |& more

59

Page 60: 숙명여대 창병모 2011 가을 1. 2 A command processor that's run in a text window  allows the user to type commands which cause actions,  can also read commands

Terminating login - Control-D

- exit

- logout

%set ignoreeof

%^D

Use “logout” to logout

%logout

Source Execute a script on the original shell

%source .login

60