unix 기초

154
UNIX 기기

Upload: roary-kirk

Post on 30-Dec-2015

61 views

Category:

Documents


0 download

DESCRIPTION

UNIX 기초. 목차. 1. UNIX 시스템 소개 2. 파일 관리 3. vi 편집기 기초 4. Shell I 5. Shell II 6. Process Control 7. Shell Programming I 8. Shell Programming II 9. 시스템 관리 기초. 1. UNIX 시스템 소개. 목 표 1. UNIX 의 특징을 이해한다. 2. Login 과 Logout 을 할 수 있다. 3. UNIX 명령어 형식을 이해한다. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: UNIX  기초

UNIX 기초

Page 2: UNIX  기초

목차

1. UNIX 시스템 소개2. 파일 관리

3. vi 편집기 기초4. Shell I

5. Shell II

6. Process Control

7. Shell Programming I

8. Shell Programming II

9. 시스템 관리 기초

Page 3: UNIX  기초

1. UNIX 시스템 소개

목 표1. UNIX 의 특징을 이해한다 .

2. Login 과 Logout 을 할 수 있다 .

3. UNIX 명령어 형식을 이해한다 .

4. 온라인 설명서를 사용할 수 있다 .

5. 기본적인 명령어들을 사용할 수 있다 .

Page 4: UNIX  기초

UNIX 소개

운영체제

UNIX 운영체제시분할 방식의 다중 작업 (Multi-tasking)

다중 사용자 환경 (Multi-user)

높은 이식성과 호환성

OperatingSystem

Users

Programs

Customers

Disks

Memory

CPU

Network

Printers

Resources

Page 5: UNIX  기초

login: user1 Login

Password:

Login message

$ date Do work

$ other commands

$ exit or <Ctrl>+d Log out

Logging In and Out

Page 6: UNIX  기초

• 형식 :$ command [-option] [argument]

• 예 :$ date

Wed Mar 31 20:33:32 JST 1999

$ ls

dira dirb f1 f2 prog1 prog2

$ ls -F

dira/ dirb/ f1 f2 prog1* prog2*

Command Line 형식

Page 7: UNIX  기초

Online 매뉴얼

• 형식 : man [-X] command

X: Manual Page Section number

• Section 번호와 내용 (HP-UX)

• 예$ man date

$ man passwd

$ man 4 passwd

1:User Commands1m:System Maintenance Commands (Section 8)2:System Calls3:Functions and Function Libraries

4:File Formats5:Miscellaneous Topics7:Device (Special) Files9:Glossary

Page 8: UNIX  기초

기본 명령어 (I)

• id 사용자 ID 와 그룹 ID 표시$ iduid=601(user1) gid=600(class)

• w 시스템 botting 시간 , load, login 사용자 정보 ( 작업 ) 표시$ w 9:00pm up 8 days, 7:31, 4 users, load average: 0.08, 0.03, 0.02User tty login@ idle JCPU PCPU whatroot console 2:46pm 129:04 -shuser3 pts/0 2:59pm w

• who 현재 login 한 사용자 정보 표시root console Mar 24 14:46user3 pts/0 Mar 31 14:59

• who am i Local 단말기와 연관된 사용자 정보 표시user3 pts/0 Mar 31 14:56

Page 9: UNIX  기초

기본 명령어 (II)

• date 시스템 날짜와 시간을 표시$ date

Fri Mar 26 14:57:42 JST 1999

• passwd Login Passwd 변경$ passwd

Changing password for user1

Old password:

New password:

Re-enter new password

Page 10: UNIX  기초

기본 명령어 (III)

• hostname 시스템의 이름을 표시$ hostname

ich01

• uname 시스템에 탑재된 운영체제에 관한 정보 표시$ uname -a

HP-UX ich01 B.10.20 U 9000/869 1426594321 unlimited-user license

• echo 메시지 표시$ echo how are youhow are you

• banner 큰 글자로 표시$ banner hi! ### # # # ### # # # ### #### # # # # # # # # # ### # # # ###

Page 11: UNIX  기초

기본 명령어 (IV)

• write login 하고 있는 user 의 terminal 로 메시지를 보냄$ write user2 [tty0p4]Hi <Return>Nice to meet you! <Return><Ctrl>+d

• mesg 메시지 수신 허용 / 불가 설정$ mesgis y$ mesg n$ mesgis n

• mail mail 사용$ mail user1 user1 에게 메일을 보냄see you again <Ctrl> + d$$ mail 받은 메일을 읽음

Page 12: UNIX  기초

2. 파일관리

File System Hierarchy

File System 기본 명령어파일관련 명령어파일 접근 / 허가

Page 13: UNIX  기초

File System Hierarchy

= file

= direc tory

/

sbin usr dev etc opt var stand tmp home

sh

contribbin lib local sbin share

sbin

ls man vi

group passwd

vmunix

user3user2user1

mail adm spoo l

Page 14: UNIX  기초

절대경로 .vs. 상대경로 (1)

• 절대경로파일이나 디렉토리의 이름을 완전하게 지정계층구조의 맨 위 ( 루트 ) 에서 시작 ( / 로 시작 )

현재위치에 상관없음 / 전체계층구조에서 고유함

• 상대경로계층구조의 현재위치에서 시작 ( / 로 시작하지 않음 )

현재위치에 대해서만 고유

• 특수디렉토리로그인 디렉토리 ( 홈 디렉토리 ) 시스템 로그인시 들어가는 디렉토리Dot (.) 현재 디렉토리Dot Dot (..) 현재 디렉토리 바로 위의 상위 디렉토리

Page 15: UNIX  기초

절대경로 .vs. 상대경로 (2)

/

tmp usr home

user3

memof1

f2

user2

f1

user1

f1bin

ls vi mancp

1

2

3

f1

4

6

5

Page 16: UNIX  기초

File System 기본 명령어

• pwd : 작업 디렉토리의 절대경로 표시• ls : 디렉토리밑의 파일 / 디렉토리 정보 표시• cd : 디렉토리 변경 • find : 파일을 찾음• mkdir : 디렉토리 생성• rmdir : 디렉토리 삭제

Page 17: UNIX  기초

File System 기본 명령어 I

• ls [dir] 디렉토리의 내용을 표시 (List Contents of a Directory)

-a 점 (.) 으로 시작하는 것을 포함하여 모든 파일 나열-d 디렉토리 특성 표시 -l 유형 , 모드 , 링크수 , 소유자 , 그룹 , 크기 (byte), 수정일 , 이름 -F 디렉토리에는 빗금 (/) 표시 , 실행가능 파일에는 * 표시 -R 하위디렉토리까지 재귀적으로 나열

• 예$ lsf1 f2 memo$ ls -Ff1 f2* memo/$ ls -aF./ .exrc .profile f1 memo/../ .login .sh_history f2*$ ls -F /homeuser1/ user2/ user3/

Page 18: UNIX  기초

File System 기본 명령어 II

• pwd 현재 작업 디렉토리를 표시 (Present Working Directory)$ pwd/home/user1

• cd 디렉토리 변경 (Change Directory)$ pwd/home/user3$ cd memo; pwd/home/user3/memo$ cd ../../; pwd/home$ cd /tmp; pwd/tmp$ cd; pwd/home/user3

Page 19: UNIX  기초

File System 기본 명령어 III

• find 파일을 찾음 형식 : find start_dir -name filename start_dir 에서 시작해서 파일 이름이

filename 인 파일을 찾는다 .start_dir 경로이름 목록 . 지정 경로로부터 재귀적으로 검색

예$ find . -name .profile

./.profile

$ find / -name f1

/home/user3/memo/f1

/home/user3/f1

$ find . -name core

Page 20: UNIX  기초

File System 기본 명령어 IV

• mkdir, rmdir 디렉토리를 만듦 , 디렉토리를 삭제형식 : mkdir [-p] dir_pathname(s) 디렉토리를 만듦

-p : 중간디렉토리가 없는 경우 생성 rmdir dir_pathname(s) 디렉토리를 삭제함

예$ lsf

f1 f2* memo/

$ mkdir fruits/apple

mkdir: cannot access fruits: No such file or directory

$ mkdir -p fruits/apple

$ rmdir fruits

rmdir: fruits: Directory not empty

$ rmdir fruits/apple fruits

Page 21: UNIX  기초

File 의 종류

• Regular Files ( 정규파일 )1. 텍스트 , 데이터 , 프로그램 원시 코드2. ls, man, date 등의 실행가능한 프로그램

• Directories ( 디렉토리 )담고 있는 파일 , 디렉토리 이름 , 파일시스템 ID 를 가지고 있는 특수 파일들

• Device Files ( 장치파일 ) 디스크 , 단말기 , 프린터 등의 하드웨어 장치에 대한 인터페이스를 제공하는 특수 파일들

Page 22: UNIX  기초

File 특성

$ ls -l-rw-r--r-- 1 user3 class 44 Mar 26 16:21 f1

-rwxr-xr-x 1 user3 class 67 Mar 26 16:22 f2

drwxrwxrwx 2 user3 class 1024 Mar 26 16:12 memo

파일유형 링크수 그룹 크기 이름Time Stamp

소유자Permissions

Page 23: UNIX  기초

파일 관련 명령어

• ls : 파일 정보 표시• cat : 파일 내용 표시• more : 파일 내용을 한 스크린 단위로 표시• tail : 파일의 끝을 표시• cp : 파일 복사• mv : 파일 / 디렉토리 이름 변경 . 파일 이동• rm : 파일 삭제• diff : 파일들의 차이를 보여줌• ln : 파일을 링크시킴

Page 24: UNIX  기초

cat 명령어

• 형식cat file [file …] 파일의 내용을 표시함

• 예$ cat f1Test file!

$ cat f2Test file, too!

$ cat f1 f2Test file!Test file, too!

$

• 간단한 파일만들기$ cat > filename <Enter>

This is test file

…..

<Ctrl> + d

$

Page 25: UNIX  기초

• 형식more filename 한화면 단위로 파일의 내용을 표시함

중간명령어f, <Ctrl>+f, <space> 다음 한 화면의 내용을 표시함b, <Ctrl>+b 이전 한 화면의 내용을 표시함q, Q 화면 표시를 중지함v 편집기로 파일을 열음h help

• 예$ more longfile

The find command recursively descends the directory hierarchy for each path name in pathname_list (that is, one or more path names) seeking files that match a Boolean expression written in the primaries given below. By default, find does not follow symbolic links

more 명령어

longfile (5%)

Page 26: UNIX  기초

• 형식head [-n number ] filename 파일의 처음 number 줄을 표시함 (default 10)

tail [-n number ] filename 파일의 마지막 number 줄을 표시함 (default 10)

tail -f [-n number ] filename -f: Follow Option.

• 예$ head -n 10 longfile ( = $ head longfile )

$ tail -n 10 longfile ( = $ tail longfile )

$ tail -f longfile ….. <Ctrl> + C $

head, tail 명령어

Page 27: UNIX  기초

cp 명령어

• 형식cp [-i] file1 new_file 파일을 다른 이름으로 복사함cp [-i] file [file …] dest_dir 파일 ( 들 ) 을 다른 디렉토리밑으로 복사함cp -r [-i] dir [dir …] dest_dir 디렉토리를 다른 디렉토리로 복사함 또

는 다른 디렉토리 밑으로 복사함-i 대화식 option.

-r 재귀적 option .

• 예$ ls -F

f1 f2* memo/ note remind

$ cp f1 f1.copy

$ ls -F

f1 f1.copy f2* memo/ note remind

$ cp note remind memo

$ ls -F memo

note remind

Page 28: UNIX  기초

mv 명령어

• 형식mv [-i] file1 new_file 파일의 이름을 바꿈mv [-i] file [file …] dest_dir 파일 ( 들 ) 을 다른 디렉토리 밑으로 이동mv [-i] dir [dir …] dest_dir 디렉토리 이름을 바꿈 또는 다른 디렉토리 밑

으로 이동-i 대화식 option.

• 예$ ls -Ff1 f2* memo/ note remind$ mv f1 file1$ ls -Ffile1 f2* memo/ note remind$ mv f2 memo/file2$ ls -Ffile1 memo/ note remind$ ls -F memofile2*

Page 29: UNIX  기초

rm 명령어

• 형식rm [-if] filename [filename ..] 파일을 삭제함rm -r [-if] filename [filename ..] 디렉토리를 삭제함

• 예$ ls -F

f1 f2* fruits/ memo/

$ rm f1; $ ls -F

f2* fruits/ memo/

$ rm -i f2

f2: ? (y/n) y

$ rm fruits

rm: fruits directory

$ rm -r fruits

Page 30: UNIX  기초

diff 명령어

• 형식diff [-i] file1 file2 파일의 내용을 비교함

-i : 대소문자를 무시함

• 예 $ cat fruit1I like fruitsappleorange

$ cat fruit2I like fruitsappleorangegrapesmelon

$ cat fruit3I like fruits very muchapplestrawberry

$ diff fruit1 fruit23a4,5> grapes> melon

$ diff fruit1 fruit31c1< I like fruits---> I like fruits very much3c3< orange---> strawberry

Page 31: UNIX  기초

ln 명령어

• 형식ln file new_file Link to a file

ln file [file …] dest_dir Link files to a directory

• 예$ ls -l f1

-rw-r--r-- 1 user3 class 44 Mar 26 16:21 f1

$ ln f1 /home/user2/f1.link

$ ls -l f1

-rw-r--r-- 2 user3 class 44 Mar 26 16:21 f1

$ ls -l /home/user2

-rw-r--r-- 2 user3 class 44 Mar 26 16:21 f1.link

$ ls -i f1 /home/user2/f1.link

97852 /home/user2/f1.link 97852 f1

Page 32: UNIX  기초

ln 명령어 (Hard Link)

• 형식ln file new_file Link to a file

ln file [file …] dest_dir Link files to a directory

• 예$ ls -l f1

-rw-r--r-- 1 user3 class 44 Mar 26 16:21 f1

$ ln f1 /home/user2/f1.link

$ ls -l f1

-rw-r--r-- 2 user3 class 44 Mar 26 16:21 f1

$ ls -l /home/user2

-rw-r--r-- 2 user3 class 44 Mar 26 16:21 f1.link

$ ls -i f1 /home/user2/f1.link

97852 /home/user2/f1.link 97852 f1

Page 33: UNIX  기초

파일 허가와 접근

• UNIX 시스템의 파일 Access 구조user( 사용자 ) : 파일의 소유자group( 그룹 ) : 파일을 액세스할수 있는 그룹other( 기타 ) : 시스템상의 다른 모든 사용자

• Access 종류 : read, write, execute

file directory

read파일의 내용을 읽을수 있다.

디렉토리의 내용을 읽을수 있다.(디렉토리가포함하고 있는 파일을 나열할 수 있다.)

write파일의 내용을 변경할수 있다.

디렉토리의 내용을 변경할 수 있다.(파일을삭제하거나 새로 생성할 수 있다.)

execute파일을 실행시킬 수있다.

디렉토리가 작업디렉토리가 될 수 있다.(cd명령으로 이동할 수 있다.)

Page 34: UNIX  기초

파일 허가와 접근 ( 예 )

$ ls -l

- rw- r-- r-- 1 user3 class 32 Mar 26 22:08 f1

- rwxr-x r-x 1 user3 class 52 Mar 26 22:09 f2

drwxr-x r-x 2 user3 class 1024 Mar 26 21:07 memo

소유자 그룹사용자

그룹기타

Page 35: UNIX  기초

허가와 접근 관련 명령어

• chmod : 파일 접근 권한 변경• umask : 기본 파일 접근 권한 변경• chown : 파일의 소유자 변경• chgrp : 파일의 그룹 변경• su : user identifier 변경• newgrp : group identifier 변경

Page 36: UNIX  기초

chmod

• 형식chmod mode_list filename ... 파일의 접근 권한 변경

mode_list: [who [operator] permission] [, … ]who user, group, other, or alloperator +(add), -(subtract), =(set equal to)permission read, write,execute

chmod numeric_mode filename … 파일의 접근 권한 변경numeric_mode 파일접근권한의 수치표현

• 예제Orginal Permission: mode user group other

rw-r--r-- rw- r-- r--New Permission: rwxr-xr-x rwx r-x r-x$ chmod u+x, g+x, o+x file or$ chmod +x file or $ chmod 755 file

Page 37: UNIX  기초

umask - 파일 모드 작성 마스크값 설정

• 형식umask 현재 파일모드 작성 마스크 값 인쇄umask mode 파일모드 작성 마스크 값 설정

• 예제user group other

default permissions: r w - r w - r w -

set default permissions: r w - r - - - - -

$ umask g-w,o-rw

$ umask 026

Page 38: UNIX  기초

chown, chgrp

• 형식chown [-R] owner filename 파일 소유자를 변경chown [-R] owner:group filename 소유자와 그룹을 같이 변경chgrp [-R] group filename 그룹 변경

• 예제$ ls -l f1-rw-r--r-- 1 user3 class 32 Mar 26 22:08 f1-rwxr-xr-x 1 user3 class 52 Mar 26 22:09 f2$ chgrp users f1$ ls -l f1-rw-r--r-- 1 user3 users 32 Mar 26 22:08 f1$ chown user2 f1$ ls -l f1-rw-r--r-- 1 user2 users 32 Mar 26 22:08 f1$ chown user3:users f2$ ls -l f2-rwxr-xr-x 1 user3 users 52 Mar 26 22:09 f2

Page 39: UNIX  기초

su - Switch User ID

• 형식su user_name user ID 와 group ID 를 바꿈 su 사용자를 root 로 전환

• 예제$ iduid=603(user3) gid=600(class)$ su user2Password:$ iduid=602(user2) gid=600(class)...$ exit or <Ctrl+d>$ iduid=603(user3) gid=600(class)

Page 40: UNIX  기초

Remote 시스템 Access & 파일 이동

• rlogin: 원격 Login

• telnet: 원격 연결• ftp: 파일전송프로토콜을 이용한 파일 복사

Page 41: UNIX  기초

telnet

• 형식telnet hostname hostname 으로 원격연결한다 .

telnet ip_address ip_address 로 원격연결한다 .

• 예제$ telnet alpha2 or telnet 105.20.19.210Trying...Connected to alpha2.Escape character is '^]'.Local flow control onTelnet TERMINAL-SPEED option ON HP-UX alpha2 B.10.20 C 9000/887 (ttyp4) login: yuhwaPassword: [alpha2:/user3/yuhwa]

Page 42: UNIX  기초

rlogin

• 형식rlogin hostname [-l username] hostname 으로 원격접속한다 .

-l username : 해당 username 으로 원격접속한다 . default 는 지역사용자 id

• 예제$ rlogin alpha2 -l yuhwa or rlogin 150.20.19.210 -l yuhwaPassword: [alpha2:/user3/yuhwa]

Page 43: UNIX  기초

ftp - file transfer program

• 형식$ ftp [ hostname] (hostname 과의 ) 파일전송 프로그램

• ftp 명령ftp> ! command 지역호스트에서 command 수행ftp> bye 현재 연결을 끊고 ftp 종료ftp> open hostname hostname 이라는 호스트에 연결을 시도ftp> close 현재의 연결을 끊음ftp> get remotefile [localfile] 원격호스트의 remotefile 을 localfile 이라는 이름으로

복사 ( 생략시는 같은 이름으로 복사 ). mget=> multi-file get

ftp> put localfile [remotefile] 지역호스트의 localfile 을 원격호스트의 remotefile 이라는 이름으로 복사 => multi-file put

ftp> bin Binary 모드로 파일을 복사ftp> asc ASCII 모드로 파일을 복사ftp> prompt Interactive 모드 제어ftp> help [command] (command 에 대한 ) help

Page 44: UNIX  기초

3. vi 편집기 기초

vi 소개기본 Command

Page 45: UNIX  기초

vi ??

• 스크린 단위 편집기 (full screen editor)- UNIX 시스템 배포시 제공되는 표준 문서 편집기- 문자를 입력하고 수정할 수 있도록 하는 대화식 편집 프로그램- 새로운 파일을 만들거나 기존 파일을 편집할 때 사용- 거의 대부분의 UNIX 시스템에서 사용

• 사용전 알아야할 기본지식- 화면전체를 이용하는 편집기이므로 터미널의 특성에 크게 의존함 .

- 네트웍을 통해 접속하는 경우 터미널 조정을 해주어야 한다$ export TERM=ansi

$ resize

- vi 를 사용하다가 갑자기 키가 멈추는 경우 : <Ctrl>+q

- vi 화면이 깨져서 보이는 경우 : <Ctrl> + l

- vi 가 갑자기 죽는 경우$ vi -r [filename]

Page 46: UNIX  기초

vi 시작하기

• 형식$ vi [filename] 기존파일 또는 새로운 파일을 편집함$ vi -R filename (cf. view) 파일을 Read Only 상태로 열음$ vi -r [filename] 재난을 당한 파일 복구

• 예$ vi sample_file

sample_file

sample_file

xxxxxxxxxx….$ vi sample_file Display

Disk

Memory

Terminal

Page 47: UNIX  기초

vi modes

• Command Mode : keystrokes 을 command 로 해석• Input Mode : keystrokes 시 파일에 입력됨• Last Line Mode : ex command 를 수행

CommandMode

InputMode

Last LineMode (ex)

: / ?

return esc

a i o A I O

Page 48: UNIX  기초

vi Session

This is Sample Text file.

~~~~~~~~

:ex commands mode message or vi 편집기 메세지

파일 내용

화면 표시를 위한 공간 보유자 ( 실제파일에는

없음 )

문자커서

Page 49: UNIX  기초

vi 끝내기

• vi 끝내기<esc> ZZ 파일을 저장하고 끝냄 ( 화면에는 표시안됨 )

<esc> :wq <Return> 파일을 저장하고 끝냄<esc> :q! <Return> 파일을 저장하지 않고 끝냄<esc> :q <Return> 파일이 변경되지 않은 경우

sample_file

sample_file <esc> :wq <Return> <esc> :q! <Return>

Disk

Memory

trash can

Page 50: UNIX  기초

Command Mode - Cursor Control

• 한글자 / 한행 단위의 이동- 커서키 (, , , ,)

- h, backspace(), j (), k (), l ()

• 단어 단위의 이동- w : 한단어씩 뒤로 이동 , W : space 로 단어를 구분- b : 한단어씩 뒤로 이동 , B : space 로 단어를 구분- e : 다음 단어의 끝으로 이동

• 줄 단위의 이동- ^, 0 : 줄의 제일 처음으로 이동- $: 줄의 제일 끝으로 이동- #G: # 줄으로 이동- return: 다음줄에서 빈칸이 아닌 첫문자로 이동

Page 51: UNIX  기초

Command Mode - Cursor Control

• 화면단위의 이동- ctrl+b: 한화면 위로 이동 ,

- ctrl+f: 한화면 아래로 이동- ctrl+u: 반화면 위로 이동- ctrl+d: 반화면 아래로 이동- H: 그 화면의 제일 윗줄로 이동- M: 그 화면의 중간줄로 이동- L: 그 화면의 마지막 줄로 이동

• 기타 명령어ctrl+l: 화면을 다시 그린다 .

ctrl+q: vi 를 사용하다가 갑자기 키가 멈추는 경우

Page 52: UNIX  기초

Command Mode - 취소 / 삭제 / 변경

• 취소- u : 직전에 내린 명령을 취소- U : 직전에 내린명령중 현재행에 해당되는 것들을 모두 취소

• 삭제- x : 현재 커서가 위치한 글자 삭제- dw : 한단어 삭제- dd : 현재줄을 모두 삭제- d$ : 커서의 현재 위치부터 줄의 끝까지 삭제- dG : 현재 위치부터 파일의 마지막까지 모두 삭제

• 변경- r : 현재 커서가 위치한 글자를 변경- cw : 현재 단어 변경- cc : 현재줄 모두 변경- cG : 커서의 현재 위치부터 줄의 끝까지 변경- R : <esc> 를 누를 때까지 모든 문자를 변경

Page 53: UNIX  기초

Command Mode - Copy & Paste

• 복사- yw: 현재 단어 복사

- yy: 현재줄 복사- yG: 현재위치에서 파일의 마지막 줄까지 복사- y$: 줄의 끝까지 복사

• 붙이기- p : 내부버퍼의 내용을 커서 뒤의 문자에 붙임- p : 내부버퍼의 내용을 커서 앞의 문자에 붙임

• 기타- . : 직전 명령 반복- J : 두줄을 합친다 .

- ctrl+G: 현재상황 ( 파일이름 , 현재라인수 , 전체라인수 , 비율 ) 표시- ~ : 대소문자 변경

Page 54: UNIX  기초

Input Mode 명령어

• Insert- i : 현재 커서 위치로부터 입력- I : 현재 커서가 있는 행의 처음부터 입력

• Append- a : 현재 커서 위치 이후로부터 입력- A : 현재 커서가 있는 행의 마지막부터 입력

• Open- o : 현재 커서가 있는 아래행부터 입력- O : 현재 커서가 있는 위행부터 입력

Page 55: UNIX  기초

특정 문자열 검색

• 검색 명령어/text : 커서의 현재 위치부터 문서의 끝방향으로 문자열 검색?text : 커서의 현재 위치부터 문서의 시작 방향으로 문자열 검색n : 이전에 찾은 문자의 다음 발생을 같은 방향으로 찾음N : 이전에 찾은 문자의 다음 발생을 반대 방향으로 찾음

• 문자열 패턴 ( 정규식 . Regular Expression)[oO]ld_text : old_text , Old_text

^text : 줄의 처음에 나오는 text

text$ : 줄의 끝에 나오는 text

. : 아무것이나 하나의 문자character* : 0 개 이상의 해당 문자

Page 56: UNIX  기초

ex 명령어 - 전체 찾기와 치환

• : m,ns/old_pattern/new_pattern/option

m, n: 명령이 실행될 시작과 끝줄 지정 . 둘다 생략되는 경우는 현재 커서가 있는 라인의 첫번째 단어

s : 치환 명령어 (substitute)

old_pattern: 검색할 명령어 (Regular Expression)

new_pattern: 바꿀 문자열option : g - 모든 단어에 대해 수행

c - 치환시 사용자에게 물어봄생략시는 각줄에서 제일 처음 나오는 단어에만 적용

Page 57: UNIX  기초

ex 명령어

• :w 현재까지의 변경사항 저장• :m,nw file m 번째 줄부터 n 번째 줄까지 file 로 저장• :w file 현재까지의 변경사항을 file 로 저장• :w! file 파일을 강제로 저장 ( 이름이 겹칠 때 )

• :e file file 을 편집할수 있는 상태로 열음• :e! 현재까지의 변경사항을 무시하고 다시 읽음• :e# 이전 파일을 편집상태로 열음• :r file file 의 내용을 현재 커서위치에 읽어들임• :! command shell command 를 수행• :set option vi 환경을 설정함 • :set nooption vi 환경설정을 취소함• :set all vi 환경 설정 option 을 모두 보여줌

Page 58: UNIX  기초

4. Shell I

개념기본 Command

Page 59: UNIX  기초

Shell 개념

• Shell 이란 ?- 사용자가 login 에 성공했을 때 , 커널이 할당해 주는 무한 loop 프로그램

• Shell 의 기능- 사용자 터미널로부터 입력을 받아들인다 .

- 입력된 명령어가 타당한지 검증한다 .

- 입력된 명령어가 타당한 경우 child process 를 생성해서 해당 명령어를 수행하고 그렇지 않을 경우 에러 메세지를 출력한다 .

whlie (True){

printf (“prompt: “);

gets (str);

execvp (str, NULL);

}

Page 60: UNIX  기초

Shell 개념

Hardware

Kernel

Shell

Users

variable assignment

environment settings

variable substitution

command substitution

filename generation

I/O redirection

pipelines

environment settings command execution

Page 61: UNIX  기초

Shell 종류

Shell Prompt 위치 비고

Bourne Shell $ /usr/old/bin/sh 가장 오래된 Shell (초기 Shell)

C Shell % /usr/bin/cshC 언어와 유사한 구문명령내역버퍼, 작업제어 기능

Korn Shell $ /usr/bin/kshBourne Shell과 호환C Shell의 장점을 따서 제작

POSIX Shell $ /usr/bin/sh POXIS 표준 준수

Page 62: UNIX  기초

Korn Shell 특징

• Command Alias

• File name completion

• Command History

• Re-entering command

• Recalling command

• Command line editing

Page 63: UNIX  기초

Aliasing

• 형식alias 현재 정의된 모든 alias 를 표시 alias name name 에 설정된 alias 표시alias name=string string 을 name 이란 이름의 alias 로 설정

• 예제$ alias dir='ls -F'$ dirf1 f2* f3 memo/ test/$ alias dirdir=ls -F

$ alias copy=cp

$ alias del='rm -i'

Page 64: UNIX  기초

File Name Completion

$ ls -l

-rw-r--r-- 1 user3 class 32 Mar 26 22:08 f1

-rwxr-xr-x 1 user3 class 52 Mar 26 22:09 f2

-rw-rw-rw- 1 user3 class 32 Mar 27 19:47 f3

-rw-rw-rw- 1 user3 class 23 Mar 27 22:05 sample.txt

$ cat sa <esc> <esc>

$ cat sample.txt <Return>

...

$ cat f <esc> <esc>

$ cat f <esc> =

1) f1

2) f2

3) f3

$ cat f <a>1

...

Page 65: UNIX  기초

Command History & Re-entering

• 형식history [-n] 입력된 최근 n 개의 명령을 표시 . 생략시 16 개history a z a 번째부터 z 번째까지의 명령을 표시r c c 번째 명령을 재실행함 또는 해당 문자로

시작하 는 가장 최근의 명령을 재실행함

• 예제$ history -2172 cat sample.txt173 cat f1$ r 173cat f1... $ r ccat f1...

Page 66: UNIX  기초

Recalling & Command Line Editing

• Recalling Commands– Prompt 에서 <esc> 를 누른다

===> 쉘이 vi 모드로 들어감– vi 명령어를 사용하여 예전에 수행했던 명령어들을 스크롤한다 .

• k : 한명령씩 이전 명령으로 이동• j : 한명령씩 최근 명령으로 이동• nG: n 번째 명령으로 이동

– <enter> 를 누르면 해당 명령어가 수행된다 .

• Command Line Editing– <esc> 를 눌러서 command 모드로 들어간다 .

– vi command 를 이용해서 line 을 편집한다 .

– <enter> 를 누르면 수정된 명령어가 수행된다 .

Page 67: UNIX  기초

사용자 환경

• 환경변수HOME 홈 디렉토리에 대한 경로 이름PATH 명령을 찾아보는 곳의 목록TERM, COLUMN, LINES 사용중인 단말기 설명LOGNAME 로그인하는데 사용한 사용자 이름HISTFILE 이전 명령어 저장EDITOR Command Line Editor 저장

• 환경 점검$ envPATH=/usr/bin:/usr/contrib/bin:/COLUMNS=80EDITOR=viLOGNAME=user3HOME=/home/user3TERM=ansiLINES=29

Page 68: UNIX  기초

사용자 환경 설정

• Shell 변수 설정 방법형식 :

$ name=value ‘=‘ 사이에 빈공간이 없어야 함예 :

$ TERM=ansi

• 중요 변수 설정PATH 쉘이 명령을 발견하기 위해 찾는 디렉토리 목록

$ PATH=/usr/bin:/usr/contrib/bin:/usr/local/bin

TERM 단말기의 종류를 설명$ TERM=vt100

PS1 Shell Prompt String 정의$ PS1=‘$PWD [!] $’

$ PS1=[`hostname`:'$PWD']

Page 69: UNIX  기초

login 절차

kernel

getty

login

/usr/bin/ksh

• displays the contents of /etc/issue• issues the login prompt• runs login

• validates user name and password• places user in home directory• runs the user’s shell

• executes /etc/profile• executes .profile• issues the shell prompt

Page 70: UNIX  기초

login 절차

kernel

getty

login

/usr/bin/ksh

• displays the contents of /etc/issue• issues the login prompt• runs login

• validates user name and password• places user in home directory• runs the user’s shell

• executes /etc/profile• executes .profile• issues the shell prompt

Page 71: UNIX  기초

Shell 변수의 종류

• 지역변수 (local variable)로컬 데이터 영역에 저장됨현재 쉘에만 속한것으로 다른 서브 프로세스에 의해 참조될수 없음export 명령어를 통해서 환경 데이터 영역으로 반출될 수 있음

• 환경변수 (environment variable)환경 데이터 영역에 저장서브 프로세스에 의해 참조될 수 있음

/usr/bin/ksh

color=bluecount=3

my_dir=/home/user3/test

PS1=$HOME=/home/user3

local variables

environmentvariables

Page 72: UNIX  기초

Display Variable Values

$ echo $HOME/home/user3

$ envPATH=/usr/bin:/usr/contrib/bin:/usr/local/bin:/home/user3:.HOME=/home/user3TERM=ansi

$ setPATH=/usr/bin:/usr/contrib/bin:/usr/local/bin:/home/user3:.HOME=/home/user3TERM=ansidir_name=memo/fruitsfile1=thisfile2=thatmy_ls=ls -aFC

Page 73: UNIX  기초

Variable Substitution

• 형식$name 해당 변수를 변수의 값으로 대체함

• 예$ echo $PATH

/usr/bin:/usr/contrib/bin:/usr/local/bin

$ PATH=$PATH:$HOME:. ; echo $PATH

/usr/bin:/usr/contrib/bin:/usr/local/bin:/home/user3:.

$ dir_name=memo/fruits ; echo $dir_name

memo/fruits

$ ls -F $dir_name

apple orange test/

$ my_ls="ls -aFC"

$ $my_ls $dir_name

./ ../ apple orange test/

Page 74: UNIX  기초

Command Substitution

• 형식$(command) 명령을 수행시킨 결과로 대체`command`

• 예$ pwd/home/user3$ curdir=$(pwd) $ echo $curdir/home/user3$ cd /tmp$ pwd/tmp$ cd $curdir$ pwd/home/user3

Page 75: UNIX  기초

Tilde Substitution

• 단어가 틸드 (~) 로 시작하면 틸드 확장이 실행됨• 예

~ 또는 ~/ HOME 변수의 설정값으로 대체~userid 해당 userid 의 홈 디렉토리~+ PWD 값으로 설정~- OLDPWD 값으로 설정

Page 76: UNIX  기초

File Name Generation

• File Name Generating Characters? 임의의 단일 문자와 일치 (앞에 오는 . 제외 )

[ ] 그중 하나와 일치하는 클래스의 문자들 지정- 두문자사이의 모든 문자를 의미! 해당 클래스를 negate

* 0 개 이상의 문자와 일치 (앞에 오는 . 제외 )

• 예$ ls -a

. .. .zz 1G 2G 7G 15G Ant Cat Dog abc abcdef cyz

$ echo [abc]?? ==> echo abc cyz

$ echo [1-9][A-Z] ==> echo 1G 2G 7G

$ echo [!A-Z]?? ==> echo 15G abc cyz

Page 77: UNIX  기초

Quoting

• 원하는 문자의 Shell 에서의 특수한 의미를 벗어나게 함• Quoting Character

backslash (\) 다음 문자의 특수한 의미를 제거함single quotes (‘) 작은 따옴표로 묶인 모든 특수문자의 특수한 의미를 제

거함double quotes (“) 큰 따옴표로 묶인 특수문자의 대부분이 이탈됨 .

예외 : \, $, { 변수이름 }, $( 명령어 )

• Shell 에서의 특수 문자White space 구분자$ 대체# 주석처리*

Page 78: UNIX  기초

5. Shell II

I/O Redirection

Filter

Pipe

Page 79: UNIX  기초

stdin, stdout, stderr

File Device

stdin

stdout

stderr

File Descriptor

0

1

2

File Descriptor

0

1

2

Page 80: UNIX  기초

Redirection

Operator 비고 예제

stdin < Input Redirection $ mail user3 < letter

> Create/Overwrite $ ps > processesstdout

>> Create/Append $ date >> processes

2> Create/Overwrite $ cp 2> cp.errstderr

2>> Create/Append $ cp 2>> cp.err

• 출력 재지정시 기존의 파일이 있으면 overwrite 함• C Shell 에서의 에러재지정 : >& 예 . # cp >& cp.err

Page 81: UNIX  기초

Filter

• 특징– 표준입력으로부터 입력을 받고 표준출력으로 출력을 내보낸다– 처리중인 파일을 수정하지 않고 결과를 화면으로 보낸다 .

– 다른 명령어의 결과값을 받아서 재처리할 때 유용 .

• 예 wc Word Count

sort Alphabetical or Numerical Sort

grep Pattern Matching

Page 82: UNIX  기초

wc

• 형식wc [-lwc] [file …] 파일안의 줄 , 단어 , 문자수를 센다 .

-l 라인수-w 단어수-c 문자수

• 예 $ cat f3This is Sample file$ wc f31 4 20 f3$ wc -l f31 f3

Page 83: UNIX  기초

sort

• 형식sort [-ndutx] [-k field_no] [file …] 파일의 line 을 sort

-n 숫자로 sort

-u 고유하게 sort. 중복되는 줄은 억제-tcharacter 분리 문자로 character 사용 . default 는 빈칸 또는 탭-k field_no 분류기준으로 삼을 필드 번호 (default 는 전체 line)

-r Reverse order 로 정렬-M 항목을 월순으로 정렬

• 예 $ tail -1 /etc/passwduser3:p88gQZpB3S/Fg:603:600:,,,:/home/user3:/usr/bin/ksh

1 2 3 4 5 6 7$ sort -nt: -k 3 /etc/passwd

Page 84: UNIX  기초

grep

• 형식grep [-cinv] patterns [file …] file 에서 patterns 을 찾는다 .

grep [-cinv] -f pattern_file [file … ]-c 일치하는 줄들의 수만 인쇄한다 .-i 패턴에서 문자의 대소문자를 구분하지 않는다 .-v 패턴이 들어있지 않은 줄만 표시-n 표시된 각 줄에 줄 번호를 붙임-f 패턴이 저장된 파일 명시-e 패턴이 2 개 이상이 경우 사용

• 예 $ grep user /etc/passwduser2:N8aQNxXWCNcJg:602:600:,,,:/home/user2:/usr/bin/kshuser3:p88gQZpB3S/Fg:603:600:,,,:/home/user3:/usr/bin/ksh$ grep -v user /etc/passwd$ grep -i user /etc/passwd$ grep ‘^user’ /etc/passwd

Page 85: UNIX  기초

정규표현식 (Regular Expression)

Regular Expression: 특별한 문자열의 형태를 기술하기 위한 메타 언어를 사용하여 만들어진 형태 기술 (pattern description)

기호 의미

. ‘\n’을 제외한 어떤 단일 글자와도 부합됨

* 앞의 표현식이 0번이상 반복되는 것에 부합됨

[] 문자열 클래스. [] 안의 어느 단일 글자와도 부합됨

^ 어떤 라인의 시작점에 부함됨

$ 어떤 라인의 마지막점에 부합됨

\ Escape Character. 뒤에 나오는 글자를 글자 그대로 해석함

+ 앞의 표현식이 1번 이상 반복되는 것에 부합됨

? 직전 정규 표현식이 0번이나 1번 반복되는 것에 부합됨

| 정규표현식이나 이후 정규표현식 둘중에 어느것이라도 부합됨

“ “ 따옴표안의 글자 그대로 해석됨

( ) 몇몇 정규표현식을 묶어서 새로운 정규표현식을 구성함

Page 86: UNIX  기초

pipe

• 파이프 (pipe): 한명령의 출력을 직접 다른 명령의 입력으로 전송• 형식

commandA | commandB | (pipe) 왼쪽에 있는 명령의 표준출력이 오른쪽에 있는 명령의 표준입력으로 사용됨

$ who > temp_file$ wc -1 < temp_file

$ rm temp_file$ who | wc -l

Page 87: UNIX  기초

pipe

command Acommand A command B command C

stderr stdout stderr stdout stderr stdout

stdin stdin

예제 : $ ps -ef | more$ ls | more$ ls | sort -r | more

* command B 는 filter 이어야 함 .

Page 88: UNIX  기초

pipe & redirection

command Acommand A command B command C

stderr stdout stderr stdout stderr stdout

stdin stdin

예제 : $ grep user /etc/passwd | sort > sorted.users$ grep user < /etc/passwd 2> grep .err | sort > sorted.users 2> sort.err$ grep user < /etc/passwd | sort 2> sort.err | wc -l > wc.out 2> wc.err

stdin

Page 89: UNIX  기초

Some Useful Commands

• wc - word, line, and byte or character count

• sort - sort or merge filesgrep

• grep - search a file for a pattern

• cut - cut out (extract) selected fields of each line of a file

• tr - translate characters

• find - find files

• xargs - construct argument list(s) and execute command

• sed - stream text editor

• awk - pattern-directed scanning and processing language

Page 90: UNIX  기초

cut

• 형식cut -c list [file … ] 파일 또는 stdin 에서 원하는cut -f list [-d char] [-s] [file …] 위치의 character 나 field 를 잘라냄option

-c character 단위로 잘라냄-f field 로 단위로 잘라냄-d -f 사용시 field 구분자 . default 는 tab. 특수문자는 quoting 필요-s -f 사용시 구분자가 없는 line 은 무시 ( 주석문 처리등에 유용 )

• 예$ dateWed Mar 31 10:51:18 JST 1999$ date | cut -c 1-3Wed$ date | cut -d " " -f 1-3Wed Mar 31

Page 91: UNIX  기초

tr

• 형식tr [-s] [string1 [string2] ] stdin 으로 들어온 characters 을 변환하여 stdout 으로 출력

tr [-d] [string1 [string2] ]

-s 연속하여 나오는 characters 를 single character 로 변환-d character 를 삭제함

• 예$ cat samplefileThis is sample file.$ cat samplefile | tr [a-z] [A-Z]THIS IS SAMPLE FILE.$ dateWed Mar 31 11:37:50 JST 1999$ date | tr [a-z] [A-Z]WED MAR 31 11:37:58 JST 1999$ date | cut -d” “ -f 1,2 | tr [a-z]" "[A-Z]"WED MAR

Page 92: UNIX  기초

find - 형식• 형식

find start_dir expressions actionsstart_dir 경로이름 목록 . 지정 경로로부터 재귀적으로 검색expressions 탐색기준 명시

-atime +n ( or -n) access 시간이 n days 이전 ( 이내 ) 인 경우 -mtime +n( or -n) modify 시간이 n days 이전 ( 이내 ) 인 경우 -ctime +n( or -n) create 시간이 n days 이전 ( 이내 ) 인 경우 -size +nc(or -n) 크기 가 n byte 보다 큰 ( 작은 ) 경우 . c 가

생략시 block 단위 -type x 파일 type 이 x 와 일치하는 경우

f Regular file d Directory b Block special file c Character special file

p FIFO (named pipe) l Symbolic link s Socket

actions 일치하는 항목을 찾았을 때 수행할 작업 명시-print 찾은 파일을 화면에 출력한다 .

-ls 찾은 파일을 long format 으로 출력한다 .

-exec 찾은 파일들을 exec 뒤의 명령에 하나씩 할당한다 .

-ok 뒤의 명령을 실행하기 전에 사용자에게 질문한다 .

Page 93: UNIX  기초

find - Example

• 예$ find . -name .profile$ find / -name f1

$ find . -name core$ find . -name core -exec rm {} \;

$ find / -mtime +7 $ find . -mtime -10 -ok rm {} \:

$ find / -size +2000$ find / -size -1000000c

$ find . -type f -exec chmod 444 {} \;

$ find . -type d -exec chmod 555 {} \;

Page 94: UNIX  기초

sed - stream editor

• 형식 sed [-n] script [file ...] file(stdin) 에서 한행씩 읽어서 script 를

수행시킨 결과를 stdout 으로 출력한다 .

sed [-n] [-e script] ... [-f script_file] ... [file ...]

-n stdout 으로 출력을 내보내지 않는다 .

-e script 가 여러개인 경우 사용-f script_file script 가 저장된 파일 이용

• 예 $ sed 's/abc/xyz/' file1 > file1.out

$ sed -e 's/abc/xyz/' -e 's/lmn/rst/' file1> file1.out

$ ls -al | sed -n '/....rwxrwx/p’ ==> $ ls -al | grep ‘….rwxrwx’

Page 95: UNIX  기초

awk - Pattern-directed scanning and processing language

• 형식awk script [filename …] 파일 ( 들 ) 을 입력으로 받아 script 를

수행함 .

awk -f script_file [filename …] 저장된 script_file 을 사용

• 예$ ls -l samplefile-rw-rw-rw- 1 user3 class 21 Mar 31 11:39 samplefile$ ls -al samplefile | awk '{print $4, $9}'class samplefile

$ cat data.txt10 20 30 40 5060 70 80 90 100$ awk ‘{print $1+$2+$3}’ data.txt60210

Page 96: UNIX  기초

awk - Pattern-directed scanning and processing language

• 형식awk script [filename …] 파일 ( 들 ) 을 입력으로 받아 script 를

수행함 .

awk -f script_file [filename …] 저장된 script_file 을 사용

• 예$ ls -l samplefile-rw-rw-rw- 1 user3 class 21 Mar 31 11:39 samplefile$ ls -al samplefile | awk '{print $4, $9}'class samplefile

$ cat data.txt10 20 30 40 5060 70 80 90 100$ awk ‘{print $1+$2+$3}’ data.txt60210

Page 97: UNIX  기초

6. Process Control

Process Control

Page 98: UNIX  기초

ps 명령어

• 형식ps [-ef] 프로세스 상태를 표시한다 .

-e 시스템에서 실행중인 모든 프로세스 정보 표시-f 프로세스 상태의 전체 목록 표시

• 예 $ ps -ef UID PID PPID C STIME TTY TIME COMMAND root 0 0 0 Mar 23 ? 0:19 swapper root 1 0 0 Mar 23 ? 0:00 init user3 3677 3676 0 23:01:16 ttyp1 0:00 ksh user3 3714 3677 0 23:03:35 ttyp1 0:00 grep user3 user3 3713 3677 5 23:03:35 ttyp1 0:00 ps -ef

Page 99: UNIX  기초

Background Processing

• 형식$ command & Background 로 작업을 수행한다 .

• 예 $ cat while_infinite while true do echo hello done$ while_infinite > test.out &[3] 18182$ ps -f UID PID PPID C STIME TTY TIME COMMAND user3 18171 17880 0 22:08:46 pts/3 0:00 cat user3 18182 17880 104 22:10:51 pts/3 0:03 -ksh user3 17880 14020 0 20:02:21 pts/3 0:00 -ksh

Page 100: UNIX  기초

Putting Jobs In Background/Foreground

• jobs 현재 수행중인 Job 표시• <Ctrl>+Z 현재 Foreground 로 수행되고 있는 Job 을 일시 중

지 (suspend) 시킴• fg [pid] or [%number] 해당 프로세스를 Foreground 로 수행시킴• bg [pid] or [%number] 해당 Job Number 를 Background 로 수행시킴

$ while_infinite &[1] 18817$ jobs[1] + Running while_infinite &$ fg 18817while_infinite <Ctrl> + Z[1] + Stopped while_infinite &$ bg[1] while_infinite &

Page 101: UNIX  기초

nohup 명령어

• 형식nohup command & 명령어가 logout 에 영향을 받지 않도록 함

• 예$ nohup while_infinite &[1] 18754Sending output to nohup.out$ exitlogoutConnection closed.login: user3Password:ps -ef | grep whileuser3 18754 1 169 09:19:40 ? 0:59 sh ./while_infinite

Page 102: UNIX  기초

kill

• 형식kill [-s signal_name] PID [PID … ] 명시된 프로세스에게 시그널을 kill [-s signal_number] PID [PID … ] 보낸다 .

-s signal_name or signal_number 프로세스에게 보내고자 하는 시그널 이름 또는 번호 . defaults 는 TERM(15)

• 예 $ while_infinite &[1] 19198$ until_infinite &[2] 19200$ kill 19198 # kill -S TERM 19198 = kill -1[1] - Terminated while_infinite &$ kill -s KILL 19200[2] + Killed until_infinite &$ kill -9 0Connection closed.

Page 103: UNIX  기초

7. Shell Programming I

소개기본

Branch

Loop

Page 104: UNIX  기초

Shell Program

• UNIX 명령어를 담고 있는 Regular 파일로 , UNIX 에서 제공되는 다른 명령어들처럼 실행시킬수 있다 .

• File Permission 은 “ r”, “x” 를 포함해야 한다 .

• 실행방법$ filename <Return> “x” permission 이 있는 경우$ ksh filename <Return> “x” permission 이 없는 경우$ ksh -x filename <Return> 쉘프로그램의 각 명령을 실행전에 표시

입력오류 등을 찾을때 유용하다 .

• Shell Program 에서 할 수 있는 일들 변수 지정 명령줄에서 인수를 받아들임 대화식 입력을 받아 들임 검사 ( 조건 Check)/ 분기 (Branch)/ 루프 (Loop)

Page 105: UNIX  기초

간단한 Shell Program 예제

$ cat myprog#this is the program myprogdatels -F$ chmod +x myprog$ myprog

ksh

ksh

date ls

P ID= 1324

P ID= 1350

P ID= 1361 P ID= 1362

$ myprog $

# date ls - F

myprog

Page 106: UNIX  기초

Shell Program 으로 데이터 전달하기

$ color=lavender$ cat color1echo You are now running program: color1echo the value of the variable color is: $color

$ ls -l color1-rw-rw-rw- 1 user3 class 89 Mar 29 11:53 color1

$ chmod +x color1$ color1You are now running program: color1the value of the variable color is:

$ export color$ color1You are now running program: color1the value of the variable color is: lavender

Page 107: UNIX  기초

Shell Program 의 Argument

• Command Line$ sh_program arg1 arg2 … argN

$0 $1 $2 … $N

• 예$ cat color3echo You are now running program: $0echo The value of command line argument \#1 is: $1echo The value of command line argument \#2 is: $2

$ chmod +x color3

$ color3 red greenYou are now running program: color3The value of command line argument #1 is: redThe value of command line argument #2 is: green

Page 108: UNIX  기초

Shell Program 의 Argument (Sample)

$ cat my_installecho $0 will install $1 to your bin directorychmod +x $1mv $1 $HOME/binecho Installation of $1 is complete!

$ chmod +x my_install$ pwd/home/user3$ mkdir bin$ my_install color3my_install will install color3 to your bin directoryInstallation of color3 is complete!

$ ls -l $HOME/bin-rwxrwxrwx 1 user3 class 139 Mar 29 11:58 color3

Page 109: UNIX  기초

특수한 Shell Variables

• 특수 Shell Variable# Command Line Arguements 의 수* 모든 Command Line Arguments

• 예$ cat color4echo There are $# command line argumentsecho They are $*echo The first command line argument is $1

$ chmod +x color4

$ color4 red green yellow blueThere are 4 command line argumentsThey are red green yellow blueThe first command line argument is red

Page 110: UNIX  기초

특수한 Shell Variables (Sample)

$ cat my_install2echo $0 will install $# files to your bin directoryecho The files to be installed are: $*chmod +x $*mv $* $HOME/binecho Installation is complete!

$ chmod +x my_install2$ my_install2 color1 color4my_install2 will install 2 files to your bin directoryThe files to be installed are: color1 color4Installation is complete!

$ ls -l $HOME/bin-rwxrwxrwx 1 user3 class 89 Mar 29 11:53 color1-rwxrwxrwx 1 user3 class 101 Mar 29 12:21 color4

Page 111: UNIX  기초

Shift 명령어

• 형식shift [n] 명령줄 인수를 n 개만큼 왼쪽으로 이동 (n 생략시 1)

• 예$ cat color5orig_args=$*echo There are $# command line arguments; echo They are $*echo Shifting two arguments; shift 2echo There are $# command line arguments; echo They are $*

$ color5 red green yellow blue orangeThere are 5 command line argumentsThey are red green yellow blue orangeShifting two argumentsThere are 3 command line argumentsThey are yellow blue orange

Page 112: UNIX  기초

Read 명령어

• 형식read variable [variable …] 사용자로부터 입력을 받아들임

• 예$ cat color6echo This program prompts for user inputecho "Please enter your favorite two colors -> \c"read color_a color_becho The colors you entered are : [$color_a] [$color_b]$ color6This program prompts for user inputPlease enter your favoriate two colors => red blue The colors you entered are : [red] [blue]$ color6This program prompts for user inputPlease enter your favoriate two colors -> red blue whiteThe colors you entered are : [red] [blue white]

Page 113: UNIX  기초

Read 명령어 (Sample)

$ cat my_install3echo $0 will install files to your bin directoryecho "Enter the names of the files -> \c"read filenameschmod +x $filenamesmv $filenames $HOME/binecho Installation is complete!

$ my_install3my_install3 will install files to your bin directoryEnter the names of the files -> f1 f2Installation is complete!

$ ls -l $HOME/bin-rwxr-xr-x 1 user3 class 32 Mar 26 22:08 f1-rwxr-xr-x 1 user3 class 52 Mar 26 22:09 f2

Page 114: UNIX  기초

Shell 함수 만들기

• 형식function funct_name {shell_script}orfunct_name ( ) {shell_script}

• 예

$ function install> {> echo Install file: $1> chmod +x $1> mv $1 $HOME/bin> echo Install complete> }$ install myfile$ install f3Install file: f3Install complete

$ install (){> echo Install file: $1> chmod +x $1> mv $1 $HOME/bin> echo Install complete> }$ install myfile$ install f3Install file: f3Install complete

or

Page 115: UNIX  기초

Return Code

• shell variable ? : holds the return code of the last command executed

0 command completed without error (true)non-zero command termiated with error (false)

• 예

$ true$ echo $?0$ ls..$ echo $?0$ echo $?0

$ false$ echo $?1$ cpUsage: cp [-f|-i] [-p] [-e warn|force|ignore] $ echo $?1$ echo $?0

Page 116: UNIX  기초

Test 명령어

• 형식test expresssion expression 을 evaluate 하고 return code 를 설정함 [ expression ]

evalutation 결과 return codetrue 0false non-zero (commonly 1)

• Test 명령어는 다음의 조건을 평가할 수 있다 .• Integer• Strings• File

Page 117: UNIX  기초

Test 명령어 - 수치 테스트

• 형식[ number1 relation number2 ] 숫자들을 relation 에 대해 비교함

relations:-lt Less than-le Less than or equal to-gt Greater than-ge Greater than or equal to-eq Equal to-ne Not equal to

• 예 (assume X=3)

$ [ $X -lt 7 ]$ echo $?0

$ [ $X -gt 7 ]$ echo $?1

Page 118: UNIX  기초

Test 명령어 - 문자열테스트

• 형식[ string1 = string2] 같은 문자열인지를 결정[ string1 != string2] 다른 문자열인지를 결정[ string ] 문자열의 길이가 0 이면 참[ -z string ] “[ -n string ] 문자열의 길이가 0 이 아니면 참

• 예

$ X=abc$ [ “$X” = “abc” ]$ echo $?0

$ X=abc$ [ “$X” != “abc” ]$ echo $?1

Page 119: UNIX  기초

Test 명령어 - 파일 테스트

• 형식[ -option filename ] 파일의 특성을 검사함test -option filename

-f 파일이 존재하고 정규 파일 ( 디렉토리 , 장치파일이 아닌 ) 이면 true-s 파일이 존재하고 크기가 0 보다 크면 true-r 파일이 존재하고 읽을수 있으면 true-w 파일이 존재하고 쓸수 있으면 true-x 파일이 존재하고 실행할수 있으면 true-d 디렉토리가 존재하면 true

• 예 $ ls -l color5-rw-rw-rw- 1 user3 class 168 Mar 29 13:37 color5$ test -f color5; echo $?0$ test -d color5; echo $?1

Page 120: UNIX  기초

Test 명령어 - 기타 연산자

• 형식-o OR-a AND! NOT\( \) GROUPING

• 예$ [ "$ANS" = y -o "$ANS" = Y ]$ [ "$NUM" -gt 10 -a "$NUM" -lt 20 ]$ test -s color3 -a -r color3$ test ! -d color3$ [ \( $# -eq 2 \) -a \( “$1” -eq “-n” \) -a \( -d “$2” -o -s “$2” \) ]

Page 121: UNIX  기초

If 구문

• 형식

• 예제

if list Athen list Bfi

if list Athen list Belse list Cfior

if test -s funfilethen echo funfile existsfi

if [ $X -lt 10 ]then echo X is less than 10else echo X is not less than 10fi

1. list A 를 수행한다 .2. 수행 결과가 참이면 list B 를 수행한다 .

1. list A 를 수행한다 .2. 수행 결과가 참이면 list B 를 수행하고 거짓이면 list C 를 수행한다 .

Page 122: UNIX  기초

Case 구문 - Multi-direcitonal branching

• 형식case word inpattern1) list A ;;pattern2) list B ;;patternN) list N ;;*) list C ;;esac

• 예제

case $ANS in yes) echo O.K. ;; no) echo Not O.K. ;; *) echo Invalid answser ;;esac

case $option in 1) echo option 1;; 2) echo option 2;; 3) echo option 3;;

*) echo no option ;;esac

word 가 pattern1 과 같으면 list A 를 수행 , pattern2 과 같으면 list B 를 수행 , …, 같은 것이 없으면 list C 를 수행한다 .

Page 123: UNIX  기초

case 구문 - sample

$ cat menu_with_caseecho COMMAND MEMUecho d to display time and dateecho w to display all login userecho l to display the contents of current direcho ""echo "Please enter your choice : \c"read choicecase $choice in [dD]*) date ;; [wW]*) who ;; [lL]*) ls ;; *) echo Invalide choice ;;esac

Page 124: UNIX  기초

Arithmetic Evaluation

• 형식let expression 산술식을 계산함(( expression ))

• 예$ x=10$ y=2$ let x=x+2$ echo $x12$ (( x=x/(y+2) ))$ echo $x3

Page 125: UNIX  기초

while 구문

• 형식while list Ado

list Bdone

• 예

조건 (list A) 가 참인 동안 list B 를 계속 수행한다 .

$ cat test_whileX=1while (( X <= 10 ))do echo X is $X; let X=X+1done$ test_whileX is 1X is 2..X is 10

Page 126: UNIX  기초

until 구문

• 형식until list Ado

list Bdone

• 예

조건 (list A) 가 참일 때까지 list B 를 계속 수행한다 .

$ cat test_untilX=1while (( X > 10 ))do echo X is $X; let X=X+1done$ test_untilX is 1X is 2..X is 10

Page 127: UNIX  기초

for 구문

• 형식for variable in list Ado

list Bdone

• 예

variable 에 list A 의 값들이 차례로 할당되면서 list B 를 수행한다 .

$ cat test_forfor X in 1 2 3 4 5do echo "2 * $X is \c" let X=X*2; echo $Xdone$ ksh test_for2 * 1 is 22 * 2 is 42 * 3 is 62 * 4 is 82 * 5 is 10

Page 128: UNIX  기초

break, continue, exit 명령어

• break 루프를 완전히 벗어난다 .

• continue 루프의 현재 반복을 멈추고 다음 반복으로 들어간다 .

• exit [n] 쉘프로그램의 수행을 정지시키고 n ( 생략시 마지막 명령문 수행 결과 ) 를 return code 로 반환한다 .

• 예제$ cat test_controlwhile truedo echo "Enter file name to remove: \c" read file if [ ! -f $file ] then echo $file is not a regular file continue fi echo removing $file rm $file break;done

Page 129: UNIX  기초

8. Shell Programming - Signal 과 trap

Signal

Trap

Page 130: UNIX  기초

Signal 이란 ?

• Signal특정 Event 가 발생했을 때 프로세스에게 보내지는 신호 (flag)

• Signal 과 Event

• kill 명령어 : 프로세스에게 특정 시그널을 보냄kill [-s signal ] pid default 는 TERM 시그널을 보냄

이름 번호 Event

EXIT Shell 이 종료됨

HUP 1Hangup. 제어단말기의 연결이 끊어졌을 때. Logout 시Backgroud 로 돌고 있는 프로세스에게 보내진다.

INT 2 Interrupt 가 발생함. <Ctrl> + C.

QUIT 3 quit. <Ctrl>+\. Core 파일을 생성KILL 9 kill

TERM 15 Software Termination

Page 131: UNIX  기초

Trap 이란 ?

• trap: 프로세스에게 전송된 시그널을 포착함수신된 신호의 종류에 따라 어떤 활동을 수행함

• 예프로그램 종료시 임시파일들을 모두 삭제한다 .중요한 작업시 INT 시그널을 무시한다 .

Page 132: UNIX  기초

Trap 명령어 - Catch Signal

• 형식trap ‘commands’ signal [signal … ] signal 을 받았을 때

commands 를 수행함• 예

$ more mytraptrap 'echo bye; exit' INT QUIT TERMwhile truedo echo hello sleep 1done$ mytraphellohello… <== <Ctrl> + Cbye$

Page 133: UNIX  기초

Trap 명령어 - Sample

• trap 을 사용한 쉘 명령 내역 파일 정리$ trap 'mv $HOME/.sh_history $HOME/.sh_hist.old' EXIT$ ls ~/.sh*/home/user3/.sh_history$ exitlogin: user3Password:$ ls -l .sh*-rw------- 1 user3 class 2694 Apr 2 18:03 .sh_hist.old-rw------- 1 user3 class 14 Apr 2 18:04 .sh_history

• 로그아웃시 몇가지 명령이 자동 실행되도록 함$ more .profiletrap “$HOME/.logout” EXIT …===> $HOME/.logout 에 로그아웃시 실행할 명령어들을 기록

Page 134: UNIX  기초

Trap 명령어 - Ignore Signal

• 형식trap ‘’ signal [signal … ] signal 을 받았을 때 아무일도 하지

않음(signal 을 무시함 )

• 예

$ more mytrap2trap '' INTwhile truedo echo hello

sleep 1done$ mytrap2hellohello <=== <Ctrl> + C : ignoredhellohello <=== <Ctrl> + \$

Page 135: UNIX  기초

Trap 의 위치

– 종료전에 특정일을 수행하는 경우• 전체 프로세스의 실행에 대해 사용될수 있도록 프로그램의 시작에

있어야 한다 .• 예 ) 종료시 임시파일을 지우는 경우

trap ‘ rm /tmp/tmpfile; exit’ INT QUIT TERM

– 중요한 일을 수행하는 동안 Signal 을 무시하려는 경우trap ‘’ INT QUIT TERM

trap INT QUIT TERM

do_critical_things

Page 136: UNIX  기초

9. 시스템 관리 기초

사용자 관리장치파일

System Startup & Shutdown

Backup & Recovery

Job Scheduling

Page 137: UNIX  기초

사용자 관리

• 사용자와 그룹의 추가 / 삭제• 관련 파일

/etc/passwd 사용자 login 정보/etc/group 그룹 정보

Page 138: UNIX  기초

/etc/passwd

• 예root::0:3::/:/sbin/shdaemon:*:1:5::/:/sbin/shuser2:N8aQNxXWCNcJg:602:600:,,,:/home/user2:/usr/bin/kshuser3:p88gQZpB3S/Fg:603:600:,,,:/home/user3:/usr/bin/ksh

• 편집시 /usr/sbin/vipw 사용• 형식 확인시 /usr/sbin/pwck 사용

user3:p88gQZpB3S/Fg:603:600:,,,:/home/user3:/usr/bin/ksh

username password user ID

group ID

home directory

startup program

Page 139: UNIX  기초

/etc/passwd

• 예root::0:3::/:/sbin/shdaemon:*:1:5::/:/sbin/shuser2:N8aQNxXWCNcJg:602:600:,,,:/home/user2:/usr/bin/kshuser3:p88gQZpB3S/Fg:603:600:,,,:/home/user3:/usr/bin/ksh

• 편집시 /usr/sbin/vipw 사용• 형식 확인시 /usr/sbin/pwck 사용

user3:p88gQZpB3S/Fg:603:600:,,,:/home/user3:/usr/bin/ksh

username password user ID

group ID

home directory

startup program

Page 140: UNIX  기초

/etc/group

• 예root::0:rootother::1:root,hpdbclass::600:user1,user2,user3student::500:user3

• 형식 확인시 /usr/sbin/grpck 사용

class: :600:user1,user2,user3

group_name

group ID

group_list

password

Page 141: UNIX  기초

사용자 생성

1. /etc/passwd 에 해당 user 정보 삽입2. /etc/group 에 해당 user 추가3. 사용자 Home directory 생성

$ mkdir /home/loginame4. 사용자 Home directory permission 변경

$ chmod 755 /home/loginname5. 필요한 파일 복사

$ cp /etc/skel/.[!.]* /home/loginname6. Home directory 소유자 / 그룹 변경

$ chown -R loginname:group /home/loginname

Page 142: UNIX  기초

사용자 생성 Shell Script

$ more user_list

user1

user2

..

user18

$ more mk_user.sh

for name in $(cat user_list)

do

mkdir /home/$name

chmod 755 /home/$name

cp /etc/skel/.[!.]* /home/$name

chmod 644 /home/${name}/.[!.]*

chown -R $name:class /home/$name

echo $name setup compelete!

done

Page 143: UNIX  기초

Device File ( 장치파일 , 특수파일 )

UNIX CommandApplications

Kernel

DeviceFile

모니터

테이프 테이프

디스크 디스크디스크

peripheral devices

Page 144: UNIX  기초

Listing Device Files

• Listing Device with ls -lbrw-r----- 1 root sys 31 0x00f000 Jun 10 1996 /dev/dsk/c0t15d0brw-r----- 1 root sys 31 0x006000 Mar 22 15:26 /dev/dsk/c0t6d0crw-r----- 1 root sys 188 0x00f000 Jun 10 1996 /dev/rdsk/c0t15d0crw-r----- 1 root sys 188 0x006000 Mar 23 14:08 /dev/rdsk/c0t6d0crwxrwxrwx 1 bin bin 193 0x000000 Jun 10 1996 /dev/tty0p0crwxrwxrwx 1 bin bin 193 0x000100 Jun 10 1996 /dev/tty0p1

Device File 유형 major # Device File 이름

minor #

Page 145: UNIX  기초

/dev 디렉토리 구조

/

dev

dev rdsk rmt ttyxpy ttydxpy

Disk Devices Tape Devices Terminals M odems

Page 146: UNIX  기초

Disk, Tape Device File Name

System SCSIDisk Tape Non-rewinding tape

Solaris /dev/rdisk/c?t?d?s? /dev/rmt/? /dev/rmt/?n

HP-UX /dev/rdisk/c?t?d?s? /dev/rmt/?m /dev/rmt/?mn

IRIX /dev/rdisk/dks?d?s? /dev/tape /dev/rmt/nrtape

SunOS /dev/rsd?? /dev/rmt? /dev/nrmt?

OSF/1 /dev/rrz? /dev/rmt?{lmh} /dev/nrmt?{lmh}

BSD1 /dev/sd?? /dev/rmt? /dev/nrmt?

• 위의 표에서 'r' 은 disk 를 raw mode 로 사용할 경우에 사용하는 이름이고 '?' 는 해당 disk

나 partition 의 숫자를 나타낸다 . c#t#d#[other]Instance number of the

interface cardSCSI target address

Device numberDevice DependentInformation

Page 147: UNIX  기초

UNIX Operating State

Multi-user Mode

Single-user Mode

Halt State

Power-Off

Shut

dow

n -hsh

utdo

wn

rebo

ot -

hpo

wer

-off

rebo

ot

shut

dow

n -r

Page 148: UNIX  기초

Booting 절차

1. 메모리 등에 대한 self-test 를 한다 .

2. 컴퓨터 기종 , host ID, ethernet address 등을 화면에 보여준다 .

3. SMD, SCSI, Network 등 boot device 로 쓰일 수 있는 것들을 검사한다 .

4. ROM 에 있는 프로그램이 boot block 을 읽어들인다 .

5. boot block 에서 boot program 을 읽어들인다 .

6. boot program 이 커널을 읽어들인다 .

7. 커널은 시스템을 초기화하고 , init 프로세스를 실행시킨다 .

init 는 RC script 를 실행시킨다 .

Page 149: UNIX  기초

압축 Utility

• tar: 여러 개의 파일을 하나의 지정된 파일로 묶음$ tar cvf < 만들 파일이름 >.tar <묶고자하는 파일이름 >

여러파일을 하나로 묶음 $ tar xvf <묶여있는 파일이름 >.tar 묶여있는 파일을 풀음$ tar tvf <묶여있는 파일이름 >.tar 묶여있는 파일 목록 확인

• compress & uncompress: 파일 압축 /압축 풀기$ compress filename filename 이 filename.Z 으로 압축됨$ uncompress filename 압축된 파일 filename.Z 가 filename 으로

압축이 풀림

• gzip : 파일 압축 /압축 풀기$ gzip filename filename 이 filename.gz 으로 압축됨$ gzip -d filename 압축된 파일 filename.gz 이 filename 으

로 압축이 풀림

Page 150: UNIX  기초

압축 Utility

• tar: 여러 개의 파일을 하나의 지정된 파일로 묶음$ tar cvf < 만들 파일이름 >.tar <묶고자하는 파일이름 >

여러파일을 하나로 묶음 $ tar xvf <묶여있는 파일이름 >.tar 묶여있는 파일을 풀음$ tar tvf <묶여있는 파일이름 >.tar 묶여있는 파일 목록 확인

• compress & uncompress: 파일 압축 /압축 풀기$ compress filename filename 이 filename.Z 으로 압축됨$ uncompress filename 압축된 파일 filename.Z 가 filename 으로

압축이 풀림

• gzip : 파일 압축 /압축 풀기$ gzip filename filename 이 filename.gz 으로 압축됨$ gzip -d filename 압축된 파일 filename.gz 이 filename 으

로 압축이 풀림

Page 151: UNIX  기초

tar 를 이용한 backup 과 restore

• 형식$ tar cvf Tape_Device_Driver filename [ filename … ]

디스크의 내용을 Tape 에 저장$ tar xvf Tape_Device_Driver Tape 의 내용을 디스크에 restore

$ tar tvf Tape_Device_Driver Tape 내의 파일 목록을 표시

• 예$ tar cvf /dev/rmt/0m * 현재 디렉토리의 내용을 Tape 에 저장

Tape 의 기존 데이터를 덮어쓴다 .$ tar xvf /dev/rmt/0m Tape 내용을 디스크에 restore$ tar tvf /dev/rmt/0m Tape 에 저장된 파일 목록 확인

Page 152: UNIX  기초

cron & crontab

• cron Daemon명령을 특정한 시간 간격으로 수행

• crontab cron 이 참조하는 table 의 생성 사용법

crontab [filename] 이미 만들어져 있는 file 의 등록 crontab -e editer 상에서 화일을 작성crontab -l 사용자의 crontab 화일을 보여줌crontab -r 사용자의 crontab 화일을 제거

Page 153: UNIX  기초

cronfile 형식

• 스페이스나 탭으로 분리된 6 개의 필드로 구성된다 .

• 첫번째에서 다섯번째 까지는 각각 시간 , 날짜 , 요일을 표시하고 여섯번째 필드는 수행될 명령어를 표시한다 .

• 예 ) crontab -l# min hourdate month day command# 0-59 0-231-31 1-12 0-6 0 * * * * /usr/bin/date > /dev/console 0 5 * * 1-5 /usr/bin/who | /usr/bin/lp 15 4 * * * find /var/preserve/ -mtime +7 -exec

rm -f {} \; > /dev/null 2>&1 0 6 * * 2,4,6 tar cvf /dev/rmt/0m ./HOME/* >

/dev/null 2>&1

Page 154: UNIX  기초

참고문헌