숙명여대 창병모 2011 가을 1. 2 a command processor that's run in a text window allows...
TRANSCRIPT
숙명여대 창병모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 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
4
변수 여러 변수 설정 및 접근 방법
프로그래밍 언어 조건 분기 , 루프 , 인터럽트 처리
Aliasing 이명을 사용한 맞춤형 명령어
History 역사 (history) 메커니즘
고급 작업 제어 (advanced job control)
5
#!/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
#!/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
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
.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
10
11
단순 변수 생성 및 배정
% 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
%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
리스트 변수 생성 및 배정% 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
%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
사전 정의 지역 변수 (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
# grep -i unix $1
# foreach i ($*)grep -i unix $i
end
17
환경 변수 생성 및 배정% 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
#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
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
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
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 ...
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
// 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
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
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
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
28
이명 공유 서브쉘에서도 이용 가능하기 위해서는 이명
정의를 ".cshrc” 에 두어야 한다 .
매개변수를 이용한 이명 역사 메커니즘을 이용하여 이미 이명된
명령어의 인자를 사용할 수 있다 .
alias cd 'cd \!*; set prompt= "$cwd \!>" '
29
30
프로그래밍 언어처럼 만들기 위해 C Shell script CGI programming in Internet
#foreach color (red yellow green blue)echo one color is $color
end
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 :
32
if.csh
#echo -n ‘enter a number: ‘set number = $<if ($number < 0) thenecho negative
else if ($number ==0) thenecho zero
elseecho positive
endif
33
if .. then ... else ... endif
if (expr) command
if (expr1) then list1else if (expr2) then list2else list3endif
34
repeat
execute a single command a specified number of time
repeat expr command
% repeat 10 echo hi there
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
36
switch ... case ... endsw
switch (expr) case pattern1: list breaksw case pattern2: case pattern3: list2 breaksw default: defaultList endsw
while … end
while (expr)commandList
end
37
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 . . .
39
junk -lp {fileName}*
기능파일을 지우는 대신에 홈 디렉토리 밑에 “ .junk” 라는 하위디렉토리에 옮긴다 . “.junk” 가 없으면 자동으로 생성한다 .
옵션-l option : “.junk” 의 현재 상태를 리스트한다 .-p option : “.junk” 휴지통 비우기
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
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: ...
#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
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
44
스크립트 없이 터미널에서 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
onintr label인터럽트가 발생하면 해당 레이블로 제어 이전
#onintr controlCwhile (1)echo infinite loopsleep2
endcontrolC:echo control-C detected
46
% 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
csh -vx script [arguments]
% csh -v menu.csh% csh -x menu.csh% csh -vx menu.csh
48
재발명하지 말라 . Unix 명령어로 해결할 수 있는 작업은 C 프로그램보다 C 스크립트로 작성하라 . 텍스트 줄을 처리하는 작업 grep, sort, awk, 등 이용
왜 스크립트를 사용하는가 생성하고 유지하기 쉽다 . 디버깅도 쉽다 .
49
스크립트을 위한 틀 리디렉션과 파이프 사용을 허용하라 인자의 수와 형태를 검사하라 파일과 디렉토리가 있는지 검사하라 적당한 오류 메시지를 내라 .
50
프로세스 생성 C 쉘은 외부 명령어를 실행하기 위해 새로운 프로세스를 생성한다 .
따라서 foreach f (`ls`) 보다는 foreach f (*) 을 사용하는 것이 좋다 .
경로명 탐색 긴 경로명은 부담이 될 수 있다 .
cd $dir foreach file ($dir/*)foreach file (*) … … end
end
51
52
A shortcut for command re-execution
The { } metacharacters
Filename substitution
Redirection
Built-in
53
54
명령어 숫자 붙이기 % set prompt='\! %' ... \! means the event number
명령어 기억 크기% set history = 40% set savehist = 32% history
역사 읽기history [-rh] [number]
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
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
파일 이름 대치 무효화 $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
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
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
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