제6장 C 쉘(C Shell)

advertisement
숙명여대 창병모
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
Step Shell type
1
both
2
login shell
3
login shell
Action
Execute commands
$HOME/.cshrc
Execute commands
"/etc/login"
Execute commands
$HOME/.login
in
in
in
8

.login 파일
 환경 변수 설정
echo -n “Enter your terminal type:”
set termtype=$<
set term=vt100
if (“$termtype” != “ “)
set term=“$termtype$”
set path=(. /bin /usr/bin /usr/local/bin)
stty erase “^?” kill “^U” intr “^C” eof “^D”
set history = 40
set prompt = “! %”

.cshrc 파일
 이명 설정 등 개인적인 설정
9
10
11

단순 변수 생성 및 배정
% set {name [= word]}*

단순 변수 접근
Syntax
$name
${name}
${?name}
Action
the value of name.
the value of name.
1 if name is set, and
0 otherwise
12
%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)

리스트 변수 접근
Syntax
$name[selector]
${name[selector]}
$#name
${#name}

Action
the element of name
whose index is
specified by selector
the number of
elements in name
리스트 구성
 리스트 끝에 새로운 원소 추가 : (list element)
14
%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)
Name
$<
$argv
Value
the next line of standard input, fully quoted
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
16
#
grep -i unix $1
#
foreach i ($*)
grep -i unix $i
end
17

환경 변수 생성 및 배정

사전 정의 환경 변수(Predefined environment variable)
% setenv name word
Name
$USER
$TERM
$PATH
$PWD
$TERMCAP
$LD_LIBRARY_PATH
$LOGNAME
Value
$user
$term
$path
$cwd
terminal's characteristic
library paths used by ld
the shell owner's user id
18
#
echo -n “do you like the C shell ?”
set reply = $<
if ($reply == “yes”) then
echo you entered yes
else if ($reply =~ y*) then
echo I assume you mean yes
endif
19
String
Meaning
Operator
==
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
20
Arithmetic
Meaning
Operator
-
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
21
%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 ...
22

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
23
// 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 16
i = 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
-r file
-w file
-x file
-o file
-z file
-f file
-d file
file
file
file
file
file
file
file
file
merely exists
exists and is readable by user
is writable by user
is executable by user
is owned by user
has size 0
is an ordinary 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

명령어
alias [word [string]]
unalias pattern

유용한 것
alias
alias
alias
alias
alias
alias
ls
rm
rm
h
ls-l
mroe
ls -F
rm -i
‘mv \!* ~/tomb’
history
ls -l
more
27

이명 공유


서브쉘에서도 이용 가능하기 위해서는 이명 정
의를 ".cshrc”에 두어야 한다.
매개변수를 이용한 이명

역사 메커니즘을 이용하여 이미 이명된 명령어
의 인자를 사용할 수 있다.
alias cd
'cd \!*; set prompt= "$cwd \!>" '
28
29

프로그래밍 언어처럼 만들기 위해


C Shell script
CGI programming in Internet
#
foreach color (red yellow green blue)
echo one color is $color
end
30
foreach
Repeat commandList, each time using a different
value in wordList for a named variable
foreach name (wordList)
commandList
end
goto
goto name
....
name :
31

if.csh
#
echo -n ‘enter a number: ‘
set number = $<
if ($number < 0) then
echo negative
else if ($number ==0) then
echo zero
else
echo positive
endif
32

if .. then ... else ... endif
if (expr) command
if (expr1) then
list1
else if (expr2) then
list2
else
list3
endif
33

repeat
execute a single command a specified number of time
repeat expr command
% repeat 10 echo hi there
34

menu.csh
#!/bin/csh
echo menu test program
set stop = 0
while ($stop == 0)
cat << ENDOFMENU
1
: print the date
2,3 : print the cwd
4
: exit
ENDOFMENU
echo -n ‘your choice ?’ ‘
set reply = $<
switch ($reply)
case “1” :
date
breaksw
case “2”:
case “3”:
pwd
breaksw
case “4”:
set stop = 1
breaksw
default:
echo illegal choice
breaksw
endsw
end
35

switch ... case ... endsw
switch (expr)
case pattern1:
list
breaksw
case pattern2:
case pattern3:
list2
breaksw
default:
defaultList
endsw
36

while … end
while (expr)
commandList
end
37
multi.csh
#
set x = 1
while ($x <= $1)
set y = 1
while ($y <= $1)
@ v = $x * $y
echo -n $v “
@ y++
end
echo “ “
@ x++
end
%multi.csh 7
1
2
3
4
5
2
4
6
8
10
3
6
9
. . .
6
12
7
14
“
38

junk -lp {fileName}*
기능
파일을 지우는 대신에 홈 디렉토리 밑에 “.junk” 라는 하위디
렉토리에 옮긴다. “.junk” 가 없으면 자동으로 생성한다.
옵션
-l option : “.junk”의 현재 상태를 리스트한다.
-p option : “.junk” 휴지통 비우기
39
#! /bin/csh
set fileList = ( )
set listFlag = 0
set purgeFlag= 0
set junk = ~/.junk
foreach arg ($*)
switch ($arg)
case “-p” :
set purgeFlag = 1
breaksw
case “-l” :
set listFlag = 1
breaksw
case -* :
echo $arg is an illegal option
goto error
breaksw
default:
set fileFlag = 1
set fileList = ($fileList $arg)
breaksw
endsw
end
40
@ total = $listFlag + $purgeFlag +$fileFlag
if ($total !=1) goto error
if (! (-e $junk)) then
‘mkdir’ $junk
endif
if ($listFlag) then
‘ls’ -lgF $junk
exit 0
endif
if ($purgeFlag) then
‘rm’ $junk/*
exit 0
endif
if ($fileFlag) then
‘mv’ $fileList $junk
exit 0
endif
exit 0
error: ...
41
#count number of files and directories in argument 1
#or current directory
#usage: numfiles [directory]
if ($#argv == 0) then
set dir = “.”
else
set dir = $argv[1]
endif
if (! -d $dir) then
echo $0\: $dir not a directory
exit 1
endif
42
echo $dir\:
@ fcount = 0
@ dcount = 0
cd $dir
foreach file (*)
if (-f $file) then
@ fcount++
else if (-d $file) then
@ dcount++
endif
end
echo $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 controlC
while (1)
echo infinite loop
sleep2
end
controlC:
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 (*)
…
end
foreach file ($dir/*)
…
end
51
52

A shortcut for command re-execution

The { } metacharacters

Filename substitution

Redirection

Built-in
53

명령어 숫자 붙이기
% set prompt='\! %'
... \! means the event number

명령어 기억 크기
% set history = 40
% set savehist = 32
% history

역사 읽기
history [-rh] [number]
54

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
55

A shortcut
Re-execute the previous command with a slight modification
^pat1^pat2
%cc fil.txt
%^fil^file

Metacharacter { }
a{b,c}d means
abd 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 >& errors
errors: 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
Download