Transcript UNIX 기초

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 명령어 형식을 이해한다.
4. 온라인 설명서를 사용할 수 있다.
5. 기본적인 명령어들을 사용할 수 있다.
UNIX 소개
운영체제
Disks
Memory
Users
Operating
System
CPU
Programs
Network
Printers
Customers
Resources
UNIX 운영체제
시분할 방식의 다중 작업 (Multi-tasking)
다중 사용자 환경 (Multi-user)
높은 이식성과 호환성
UNIX 소개 (계속)
Logging In and Out
login: user1
Password:
$ date
$ other commands
$ exit or <Ctrl>+d
Login
Login message
Do work
Log out
Command Line 형식
• 형식:
$ 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*
Online 매뉴얼
• 형식:
man [-X] command
X: Manual Page Section number
• Section 번호와 내용 (HP-UX)
1:User Commands
1m:System Maintenance Commands
(Section 8)
2:System Calls
3:Functions and Function Libraries
• 예
$ man date
$ man passwd
$ man 4 passwd
4:File Formats
5:Miscellaneous Topics
7:Device (Special) Files
9:Glossary
기본 명령어 (I)
• id
사용자 ID 와 그룹 ID 표시
$ id
uid=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.02
User tty
login@
idle
JCPU PCPU
what
root console
2:46pm
129:04
-sh
user3 pts/0
2:59pm
w
• who
root
user3
현재 login 한 사용자 정보 표시
console
pts/0
• who am i
user3
Mar 24 14:46
Mar 31 14:59
Local 단말기와 연관된 사용자 정보 표시
pts/0
Mar 31 14:56
기본 명령어 (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
기본 명령어 (III)
• hostname
시스템의 이름을 표시
$ hostname
ich01
• uname
시스템에 탑재된 운영체제에 관한 정보 표시
$ uname -a
HP-UX ich01 B.10.20 U 9000/869 1426594321 unlimited-user license
• echo
메시지 표시
$ echo how are you
how are you
• banner
큰 글자로 표시
$ banner hi!
# #
# #
####
# #
# #
# #
#
#
#
#
#
#
###
###
###
##
###
###
기본 명령어 (IV)
• write
login 하고 있는 user의 terminal 로 메시지를 보냄
$ write user2 [tty0p4]
Hi
<Return>
Nice to meet you!
<Return>
<Ctrl>+d
• mesg
메시지 수신 허용/불가 설정
$ mesg
is y
$ mesg n
$ mesg
is n
• mail
mail 사용
user1 에게 메일을 보냄
$ mail user1
see you again <Ctrl> + d
$
$ mail
받은 메일을 읽음
기본 명령어 (IV)
• mail 계속
2. 파일관리
File System Hierarchy
File System 기본 명령어
파일관련 명령어
파일 접근/허가
File System Hierarchy
/
sbin
usr
dev
etc
opt
var
stand
tmp
home
vmunix
group
passwd
user1
mail
bin
contrib
lib
local
sbin
adm
user2
user3
spool
share
sbin
sh
ls
man
vi
= directory
= file
절대경로 .vs. 상대경로 (1)
• 절대경로
파일이나 디렉토리의 이름을 완전하게 지정
계층구조의 맨 위(루트)에서 시작 ( / 로 시작)
현재위치에 상관없음/전체계층구조에서 고유함
• 상대경로
계층구조의 현재위치에서 시작 ( / 로 시작하지 않음)
현재위치에 대해서만 고유
• 특수디렉토리
로그인 디렉토리(홈 디렉토리) 시스템 로그인시 들어가는 디렉토리
Dot (.)
현재 디렉토리
Dot Dot (..)
현재 디렉토리 바로 위의 상위 디렉토리
절대경로 .vs. 상대경로 (2)
4
/
tmp
home
usr
5
f1
user1
user2
f1
f1
user3
3
bin
1
f1
memo
6
cp
ls
vi
man
2
f2
File System 기본 명령어
•
•
•
•
•
•
pwd
ls
cd
find
mkdir
rmdir
: 작업 디렉토리의 절대경로 표시
: 디렉토리밑의 파일/디렉토리 정보 표시
: 디렉토리 변경
: 파일을 찾음
: 디렉토리 생성
: 디렉토리 삭제
File System 기본 명령어 I
• ls [dir]
-a
-d
-l
-F
-R
디렉토리의 내용을 표시 (List Contents of a Directory)
점(.)으로 시작하는 것을 포함하여 모든 파일 나열
디렉토리 특성 표시
유형, 모드, 링크수, 소유자, 그룹, 크기 (byte), 수정일, 이름
디렉토리에는 빗금 (/) 표시, 실행가능 파일에는 * 표시
하위디렉토리까지 재귀적으로 나열
• 예
$ ls
f1 f2 memo
$ ls -F
f1 f2* memo/
$ ls -aF
./
.exrc
.profile f1
../
.login
.sh_history f2*
$ ls -F /home
user1/ user2/
user3/
memo/
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
File System 기본 명령어 III
• find
파일을 찾음
형식: find start_dir -name filename
start_dir
start_dir 에서 시작해서 파일 이름이
filename 인 파일을 찾는다.
경로이름 목록. 지정 경로로부터 재귀적으로 검색
예
$ find . -name .profile
./.profile
$ find / -name f1
/home/user3/memo/f1
/home/user3/f1
$ find . -name core
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
File 의 종류
• Regular Files (정규파일)
1. 텍스트, 데이터, 프로그램 원시 코드
2. ls, man, date 등의 실행가능한 프로그램
• Directories (디렉토리)
담고 있는 파일, 디렉토리 이름, 파일시스템 ID 를 가지고 있는 특수 파일들
• Device Files (장치파일)
디스크, 단말기, 프린터 등의 하드웨어 장치에 대한 인터페이스를 제공하는
특수 파일들
File 특성
$ ls -l
-rw-r--r-1 user3
-rwxr-xr-x
1 user3
drwxrwxrwx 2 user3
파일유형
링크수
Permissions
소유자
class
class
class
44 Mar 26 16:21 f1
67 Mar 26 16:22 f2
1024 Mar 26 16:12 memo
그룹
크기 Time Stamp 이름
파일 관련 명령어
•
•
•
•
•
•
•
•
•
ls
cat
more
tail
cp
mv
rm
diff
ln
: 파일 정보 표시
: 파일 내용 표시
: 파일 내용을 한 스크린 단위로 표시
: 파일의 끝을 표시
: 파일 복사
: 파일/디렉토리 이름 변경. 파일 이동
: 파일 삭제
: 파일들의 차이를 보여줌
: 파일을 링크시킴
cat 명령어
• 형식
cat file [file …]
• 예
$ cat f1
Test file!
파일의 내용을 표시함
• 간단한 파일만들기
$ cat > filename <Enter>
This is test file
$ cat f2
Test file, too!
$ cat f1 f2
Test file!
Test file, too!
$
…..
<Ctrl> + d
$
more 명령어
• 형식
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
longfile (5%)
head, tail 명령어
• 형식
head [-n number ] filename
tail [-n number ] filename
tail -f [-n number ] filename
파일의 처음 number 줄을 표시함 (default 10)
파일의 마지막 number 줄을 표시함 (default 10)
-f: Follow Option.
• 예
$ head -n 10 longfile
$ tail -n 10 longfile
$ tail -f longfile
…..
<Ctrl> + C
$
( = $ head longfile )
( = $ tail longfile )
cp 명령어
• 형식
cp [-i] file1 new_file
cp [-i] file [file …] dest_dir
cp -r [-i] dir [dir …] dest_dir
-i
-r
대화식 option.
재귀적 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
파일을 다른 이름으로 복사함
파일(들)을 다른 디렉토리밑으로 복사함
디렉토리를 다른 디렉토리로 복사함 또
는 다른 디렉토리 밑으로 복사함
mv 명령어
• 형식
mv [-i] file1 new_file
mv [-i] file [file …] dest_dir
mv [-i] dir [dir …] dest_dir
-i
대화식 option.
• 예
$ ls -F
f1 f2* memo/ note remind
$ mv f1 file1
$ ls -F
file1 f2* memo/ note remind
$ mv f2 memo/file2
$ ls -F
file1 memo/ note remind
$ ls -F memo
file2*
파일의 이름을 바꿈
파일(들)을 다른 디렉토리 밑으로 이동
디렉토리 이름을 바꿈 또는 다른 디렉토리 밑
으로 이동
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
파일을 삭제함
디렉토리를 삭제함
diff 명령어
• 형식
diff [-i] file1 file2
파일의 내용을 비교함
-i :
대소문자를 무시함
• 예
$ cat fruit1
I like fruits
apple
orange
$ diff fruit1
fruit2
3a4,5
> grapes
> melon
$ cat fruit2
I like fruits
apple
orange
grapes
melon
$ cat fruit3
I like fruits very much
apple
strawberry
$ diff fruit1 fruit3
1c1
< I like fruits
--> I like fruits very much
3c3
< orange
--> strawberry
ln 명령어
• 형식
ln file new_file
ln file [file …] dest_dir
Link to a file
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
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
파일 허가와 접근
• UNIX 시스템의 파일 Access 구조
: 파일의 소유자
: 파일을 액세스할수 있는 그룹
: 시스템상의 다른 모든 사용자
user(사용자)
group(그룹)
other(기타)
• Access 종류: read, write, execute
file
directory
read
파일의 내용을
수 있다.
읽을 디렉토리의 내용을 읽을수 있다.(디렉토리가
포함하고 있는 파일을 나열할 수 있다.)
write
파일의 내용을
할수 있다.
변경 디렉토리의 내용을 변경할 수 있다.(파일을
삭제하거나 새로 생성할 수 있다.)
파일을
execute 있다.
실행시킬
수 디렉토리가 작업디렉토리가 될 수 있다.(cd
명령으로 이동할 수 있다.)
파일 허가와 접근 (예)
$ ls -l
- rw- r-- r-- 1 user3
- rwxr-x r-x 1 user3
drwxr-x r-x 2 user3
사용자
그룹
기타
소유자
class
class
class
그룹
32 Mar 26 22:08 f1
52 Mar 26 22:09 f2
1024 Mar 26 21:07 memo
허가와 접근 관련 명령어
•
•
•
•
•
•
chmod
umask
chown
chgrp
su
newgrp
: 파일 접근 권한 변경
: 기본 파일 접근 권한 변경
: 파일의 소유자 변경
: 파일의 그룹 변경
: user identifier 변경
: group identifier 변경
chmod
• 형식
chmod mode_list filename ...
파일의 접근 권한 변경
mode_list: [who [operator] permission] [, … ]
who
operator
permission
user, group, other, or all
+(add), -(subtract), =(set equal to)
read, write,execute
chmod numeric_mode filename …
파일의 접근 권한 변경
numeric_mode
파일접근권한의 수치표현
• 예제
Orginal Permission:
mode
user
rw-r--r-rwNew Permission:
rwxr-xr-x
rwx
$ chmod u+x, g+x, o+x file or $ chmod +x file
group
other
r-r-r-x
r-x
or $ chmod 755 file
umask - 파일 모드 작성 마스크값 설정
• 형식
umask
umask
현재 파일모드 작성 마스크 값 인쇄
파일모드 작성 마스크 값 설정
mode
• 예제
default permissions:
set default permissions:
$ umask
$ umask
g-w,o-rw
026
user
rwrw-
group
rwr - -
other
rw- - -
chown, chgrp
• 형식
chown [-R] owner filename
chown [-R] owner:group filename
chgrp [-R] group filename
파일 소유자를 변경
소유자와 그룹을 같이 변경
그룹 변경
• 예제
$ ls -l f1
-rw-r--r-- 1 user3 class
-rwxr-xr-x 1 user3 class
$ chgrp users f1
$ ls -l f1
-rw-r--r-- 1 user3 users
$ chown user2 f1
$ ls -l f1
-rw-r--r-- 1 user2 users
$ chown user3:users f2
$ ls -l f2
-rwxr-xr-x 1 user3 users
32 Mar 26 22:08 f1
52 Mar 26 22:09 f2
32 Mar 26 22:08 f1
32 Mar 26 22:08 f1
52 Mar 26 22:09 f2
su - Switch User ID
• 형식
su user_name
su
user ID 와 group ID 를 바꿈
사용자를 root 로 전환
• 예제
$ id
uid=603(user3) gid=600(class)
$ su user2
Password:
$ id
uid=602(user2) gid=600(class)
...
$ exit or <Ctrl+d>
$ id
uid=603(user3) gid=600(class)
Remote 시스템 Access & 파일 이동
• rlogin: 원격 Login
• telnet: 원격 연결
• ftp: 파일전송프로토콜을 이용한 파일 복사
telnet
• 형식
telnet hostname
telnet ip_address
hostname 으로 원격연결한다.
ip_address로 원격연결한다.
• 예제
$ telnet alpha2
or
telnet 105.20.19.210
Trying...
Connected to alpha2.
Escape character is '^]'.
Local flow control on
Telnet TERMINAL-SPEED option ON
HP-UX alpha2 B.10.20 C 9000/887 (ttyp4)
login: yuhwa
Password:
[alpha2:/user3/yuhwa]
rlogin
• 형식
rlogin hostname [-l username]
hostname 으로 원격접속한다.
-l username: 해당 username으로 원격접속한다. default 는 지역사용자 id
• 예제
$ rlogin alpha2 -l yuhwa
Password:
[alpha2:/user3/yuhwa]
or rlogin 150.20.19.210 -l yuhwa
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
3. vi 편집기 기초
vi 소개
기본 Command
vi ??
• 스크린 단위 편집기 (full screen editor)
- UNIX 시스템 배포시 제공되는 표준 문서 편집기
- 문자를 입력하고 수정할 수 있도록 하는 대화식 편집 프로그램
- 새로운 파일을 만들거나 기존 파일을 편집할 때 사용
- 거의 대부분의 UNIX 시스템에서 사용
• 사용전 알아야할 기본지식
- 화면전체를 이용하는 편집기이므로 터미널의 특성에 크게 의존함.
- 네트웍을 통해 접속하는 경우 터미널 조정을 해주어야 한다
$ export TERM=ansi
$ resize
- vi 를 사용하다가 갑자기 키가 멈추는 경우: <Ctrl>+q
- vi 화면이 깨져서 보이는 경우: <Ctrl> + l
- vi 가 갑자기 죽는 경우
$ vi -r [filename]
vi 시작하기
• 형식
$ vi [filename]
$ vi -R filename (cf. view)
$ vi -r [filename]
기존파일 또는 새로운 파일을 편집함
파일을 Read Only 상태로 열음
재난을 당한 파일 복구
• 예
$ vi sample_file
Memory
Disk
sample_file
sample_file
$ vi sample_file
Terminal
Display
xxxxxxx
xxx….
vi modes
• Command Mode
• Input Mode
• Last Line Mode
Last Line
Mode (ex)
: keystrokes 을 command 로 해석
: keystrokes 시 파일에 입력됨
: ex command를 수행
: / ?
return
Command
Mode
a i o A I O
esc
Input
Mode
vi Session
This is Sample Text file.
파일 내용
문자커서
~
~
~
~
~
~
~
~
화면 표시를 위한 공간 보
유자(실제파일에는 없음)
:ex commands
or
vi 편집기 메세지
mode message
vi 끝내기
• vi 끝내기
<esc> ZZ
<esc> :wq <Return>
<esc> :q! <Return>
<esc> :q <Return>
파일을 저장하고 끝냄 (화면에는 표시안됨)
파일을 저장하고 끝냄
파일을 저장하지 않고 끝냄
파일이 변경되지 않은 경우
Memory
trash can
Disk
sample_file
sample_file
<esc> :wq <Return>
<esc> :q! <Return>
Command Mode - Cursor Control
• 한글자/한행 단위의 이동
- 커서키(,  , , ,)
- h, backspace(), j (), k (), l ()
• 단어 단위의 이동
- w :한단어씩 뒤로 이동, W : space 로 단어를 구분
- b : 한단어씩 뒤로 이동, B : space 로 단어를 구분
- e : 다음 단어의 끝으로 이동
• 줄 단위의 이동
- ^, 0 : 줄의 제일 처음으로 이동
- $: 줄의 제일 끝으로 이동
- #G: # 줄으로 이동
- return: 다음줄에서 빈칸이 아닌 첫문자로 이동
Command Mode - Cursor Control
• 화면단위의 이동
- ctrl+b: 한화면 위로 이동,
- ctrl+f: 한화면 아래로 이동
- ctrl+u: 반화면 위로 이동
- ctrl+d: 반화면 아래로 이동
- H: 그 화면의 제일 윗줄로 이동
- M: 그 화면의 중간줄로 이동
- L: 그 화면의 마지막 줄로 이동
• 기타 명령어
ctrl+l: 화면을 다시 그린다.
ctrl+q: vi 를 사용하다가 갑자기 키가 멈추는 경우
Command Mode - 취소/삭제/변경
• 취소
- u : 직전에 내린 명령을 취소
- U : 직전에 내린명령중 현재행에 해당되는 것들을 모두 취소
• 삭제
- x : 현재 커서가 위치한 글자 삭제
- dw : 한단어 삭제
- dd : 현재줄을 모두 삭제
- d$ : 커서의 현재 위치부터 줄의 끝까지 삭제
- dG : 현재 위치부터 파일의 마지막까지 모두 삭제
• 변경
- r : 현재 커서가 위치한 글자를 변경
- cw : 현재 단어 변경
- cc : 현재줄 모두 변경
- cG : 커서의 현재 위치부터 줄의 끝까지 변경
- R : <esc> 를 누를 때까지 모든 문자를 변경
Command Mode - Copy & Paste
• 복사
- yw: 현재 단어 복사
- yy: 현재줄 복사
- yG: 현재위치에서 파일의 마지막 줄까지 복사
- y$: 줄의 끝까지 복사
• 붙이기
- p : 내부버퍼의 내용을 커서 뒤의 문자에 붙임
- p : 내부버퍼의 내용을 커서 앞의 문자에 붙임
• 기타
- . : 직전 명령 반복
- J : 두줄을 합친다.
- ctrl+G: 현재상황 (파일이름, 현재라인수, 전체라인수, 비율) 표시
- ~ : 대소문자 변경
Input Mode 명령어
• Insert
- i : 현재 커서 위치로부터 입력
- I : 현재 커서가 있는 행의 처음부터 입력
• Append
- a : 현재 커서 위치 이후로부터 입력
- A : 현재 커서가 있는 행의 마지막부터 입력
• Open
- o : 현재 커서가 있는 아래행부터 입력
- O : 현재 커서가 있는 위행부터 입력
특정 문자열 검색
• 검색 명령어
/text : 커서의 현재 위치부터 문서의 끝방향으로 문자열 검색
?text : 커서의 현재 위치부터 문서의 시작 방향으로 문자열 검색
n
: 이전에 찾은 문자의 다음 발생을 같은 방향으로 찾음
N
: 이전에 찾은 문자의 다음 발생을 반대 방향으로 찾음
• 문자열 패턴 (정규식. Regular Expression)
[oO]ld_text : old_text , Old_text
^text : 줄의 처음에 나오는 text
text$ : 줄의 끝에 나오는 text
.
: 아무것이나 하나의 문자
character* : 0개 이상의 해당 문자
ex 명령어 - 전체 찾기와 치환
• : m,ns/old_pattern/new_pattern/option
m, n: 명령이 실행될 시작과 끝줄 지정. 둘다 생략되는 경우는 현재 커서가 있는
라인의 첫번째 단어
s : 치환 명령어(substitute)
old_pattern: 검색할 명령어(Regular Expression)
new_pattern: 바꿀 문자열
option :
g - 모든 단어에 대해 수행
c - 치환시 사용자에게 물어봄
생략시는 각줄에서 제일 처음 나오는 단어에만 적용
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을 모두 보여줌
4. Shell I
개념
기본 Command
Shell 개념
• Shell 이란?
- 사용자가 login 에 성공했을 때, 커널이 할당해 주는 무한loop 프로그램
• Shell 의 기능
- 사용자 터미널로부터 입력을 받아들인다.
- 입력된 명령어가 타당한지 검증한다.
- 입력된 명령어가 타당한 경우 child process를 생성해서 해당 명령어를 수행하
고 그렇지 않을 경우 에러 메세지를 출력한다.
whlie (True){
printf (“prompt: “);
gets (str);
execvp (str, NULL);
}
Shell 개념
Users
environment settings
Shell
command execution
Kernel
environment settings
pipelines
Hardware
variable assignment
I/O redirection
variable substitution
filename generation
command substitution
Shell 종류
위치
비고
Shell
Prompt
Bourne Shell
$
/usr/old/bin/sh
가장 오래된 Shell (초기 Shell)
C Shell
%
/usr/bin/csh
C 언어와 유사한 구문
명령내역버퍼, 작업제어 기능
Korn Shell
$
/usr/bin/ksh
Bourne Shell 과 호환
C Shell 의 장점을 따서 제작
POSIX Shell
$
/usr/bin/sh
POXIS 표준 준수
Korn Shell 특징
•
•
•
•
•
•
Command Alias
File name completion
Command History
Re-entering command
Recalling command
Command line editing
Aliasing
• 형식
alias
alias name
alias name=string
현재 정의된 모든 alias 를 표시
name 에 설정된 alias 표시
string 을 name 이란 이름의 alias 로 설정
• 예제
$ alias dir='ls -F'
$ dir
f1 f2* f3 memo/ test/
$ alias dir
dir=ls -F
$ alias copy=cp
$ alias del='rm -i'
File Name Completion
$ ls -l
-rw-r--r-- 1 user3 class
-rwxr-xr-x 1 user3 class
-rw-rw-rw- 1 user3 class
-rw-rw-rw- 1 user3 class
$ 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
...
32 Mar 26 22:08 f1
52 Mar 26 22:09 f2
32 Mar 27 19:47 f3
23 Mar 27 22:05 sample.txt
Command History & Re-entering
• 형식
history [-n]
history a z
r c
• 예제
$ history -2
172 cat sample.txt
173 cat f1
$ r 173
cat f1
...
$rc
cat f1
...
입력된 최근 n 개의 명령을 표시. 생략시 16개
a번째부터 z번째까지의 명령을 표시
c번째 명령을 재실행함 또는 해당 문자로 시작하
는 가장 최근의 명령을 재실행함
Recalling & Command Line Editing
• Recalling Commands
– Prompt 에서 <esc> 를 누른다
===> 쉘이 vi 모드로 들어감
– vi 명령어를 사용하여 예전에 수행했던 명령어들을 스크롤한다.
• k : 한명령씩 이전 명령으로 이동
• j : 한명령씩 최근 명령으로 이동
• nG: n번째 명령으로 이동
– <enter> 를 누르면 해당 명령어가 수행된다.
• Command Line Editing
– <esc> 를 눌러서 command 모드로 들어간다.
– vi command 를 이용해서 line 을 편집한다.
– <enter> 를 누르면 수정된 명령어가 수행된다.
사용자 환경
• 환경변수
HOME
홈 디렉토리에 대한 경로 이름
PATH
명령을 찾아보는 곳의 목록
TERM, COLUMN, LINES
사용중인 단말기 설명
LOGNAME 로그인하는데 사용한 사용자 이름
HISTFILE
이전 명령어 저장
EDITOR
Command Line Editor 저장
• 환경 점검
$ env
PATH=/usr/bin:/usr/contrib/bin:/
COLUMNS=80
EDITOR=vi
LOGNAME=user3
HOME=/home/user3
TERM=ansi
LINES=29
사용자 환경 설정
• 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']
login 절차
kernel
getty
• displays the contents of /etc/issue
• issues the login prompt
• runs login
login
• validates user name and password
• places user in home directory
• runs the user’s shell
/usr/bin/ksh
• executes /etc/profile
• executes .profile
• issues the shell prompt
login 절차
kernel
getty
• displays the contents of /etc/issue
• issues the login prompt
• runs login
login
• validates user name and password
• places user in home directory
• runs the user’s shell
/usr/bin/ksh
• executes /etc/profile
• executes .profile
• issues the shell prompt
Shell 변수의 종류
• 지역변수 (local variable)
로컬 데이터 영역에 저장됨
현재 쉘에만 속한것으로 다른 서브 프
로세스에 의해 참조될수 없음
export 명령어를 통해서 환경 데이터 영
역으로 반출될 수 있음
local variables
color=blue
count=3
my_dir=/home/user3/test
/usr/bin/ksh
• 환경변수 (environment variable)
환경 데이터 영역에 저장
서브 프로세스에 의해 참조될 수 있음
PS1=$
HOME=/home/user3
environment
variables
Display Variable Values
$ echo $HOME
/home/user3
$ env
PATH=/usr/bin:/usr/contrib/bin:/usr/local/bin:/home/user3:.
HOME=/home/user3
TERM=ansi
$ set
PATH=/usr/bin:/usr/contrib/bin:/usr/local/bin:/home/user3:.
HOME=/home/user3
TERM=ansi
dir_name=memo/fruits
file1=this
file2=that
my_ls=ls -aFC
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/
Command Substitution
• 형식
$(command)
`command`
• 예
$ pwd
/home/user3
$ curdir=$(pwd)
$ echo $curdir
/home/user3
$ cd /tmp
$ pwd
/tmp
$ cd $curdir
$ pwd
/home/user3
명령을 수행시킨 결과로 대체
Tilde Substitution
• 단어가 틸드(~)로 시작하면 틸드 확장이 실행됨
• 예
~ 또는 ~/
~userid
~+
~-
HOME 변수의 설정값으로 대체
해당 userid 의 홈 디렉토리
PWD 값으로 설정
OLDPWD 값으로 설정
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
Quoting
• 원하는 문자의 Shell 에서의 특수한 의미를 벗어나게 함
• Quoting Character
backslash (\)
single quotes (‘)
double quotes (“)
다음 문자의 특수한 의미를 제거함
작은 따옴표로 묶인 모든 특수문자의 특수한 의미를 제
거함
큰 따옴표로 묶인 특수문자의 대부분이 이탈됨.
예외: \, $, {변수이름}, $(명령어)
• Shell 에서의 특수 문자
White space
$
#
*
구분자
대체
주석처리
5. Shell II
I/O Redirection
Filter
Pipe
stdin, stdout, stderr
File
Device
File Descriptor
stdin
0
stdout
1
stderr
2
Redirection
stdin
Operator
비고
예제
<
Input Redirection
$ mail
>
Create/Overwrite
$ ps > processes
>>
Create/Append
$ date >> processes
2>
Create/Overwrite
$ cp 2> cp.err
Create/Append
$ cp 2>> cp.err
user3 < letter
stdout
stderr
2>>
• 출력 재지정시 기존의 파일이 있으면 overwrite 함
• C Shell 에서의 에러재지정: >& 예. # cp >& cp.err
Filter
• 특징
– 표준입력으로부터 입력을 받고 표준출력으로 출력을 내보낸다
– 처리중인 파일을 수정하지 않고 결과를 화면으로 보낸다.
– 다른 명령어의 결과값을 받아서 재처리할 때 유용.
• 예
wc
sort
grep
Word Count
Alphabetical or Numerical Sort
Pattern Matching
wc
• 형식
wc [-lwc]
-l
-w
-c
[file …]
라인수
단어수
문자수
• 예
$ cat f3
This is Sample file
$ wc f3
1 4 20 f3
$ wc -l f3
1 f3
파일안의 줄, 단어, 문자수를 센다.
sort
• 형식
sort [-ndutx]
-n
-u
-tcharacter
-k field_no
-r
-M
[-k field_no] [file …]
파일의 line 을 sort
숫자로 sort
고유하게 sort. 중복되는 줄은 억제
분리 문자로 character 사용. default는 빈칸 또는 탭
분류기준으로 삼을 필드 번호 (default 는 전체 line)
Reverse order 로 정렬
항목을 월순으로 정렬
• 예
$ tail -1 /etc/passwd
user3:p88gQZpB3S/Fg:603:600:,,,:/home/user3:/usr/bin/ksh
1
2
3 4 5
6
7
$ sort -nt: -k 3 /etc/passwd
grep
• 형식
grep [-cinv]
grep [-cinv]
-c
-i
-v
-n
-f
-e
patterns [file …]
file 에서 patterns 을 찾는다.
-f pattern_file [file … ]
일치하는 줄들의 수만 인쇄한다.
패턴에서 문자의 대소문자를 구분하지 않는다.
패턴이 들어있지 않은 줄만 표시
표시된 각 줄에 줄 번호를 붙임
패턴이 저장된 파일 명시
패턴이 2개 이상이 경우 사용
• 예
$ grep user /etc/passwd
user2:N8aQNxXWCNcJg:602:600:,,,:/home/user2:/usr/bin/ksh
user3:p88gQZpB3S/Fg:603:600:,,,:/home/user3:/usr/bin/ksh
$ grep -v user /etc/passwd
$ grep -i user /etc/passwd
$ grep ‘^user’ /etc/passwd
정규표현식 (Regular Expression)
Regular Expression: 특별한 문자열의 형태를 기술하기 위한 메타 언어를 사용하
여 만들어진 형태 기술 (pattern description)
기호
의미
‘\n’을 제외한 어떤 단일 글자와도 부합됨
앞의 표현식이 0 번이상 반복되는 것에 부합됨
.
*
^
문자열 클래스. [] 안의 어느 단일 글자와도 부합됨
어떤 라인의 시작점에 부함됨
$
어떤 라인의 마지막점에 부합됨
\
Escape Character. 뒤에 나오는 글자를 글자 그대로 해석함
앞의 표현식이 1 번 이상 반복되는 것에 부합됨
[]
+
직전 정규 표현식이 0 번이나 1 번 반복되는 것에 부합됨
정규표현식이나 이후 정규표현식 둘중에 어느것이라도 부합됨
?
|
“
“
()
따옴표안의 글자 그대로 해석됨
몇몇 정규표현식을 묶어서 새로운 정규표현식을 구성함
pipe
• 파이프(pipe): 한명령의 출력을 직접 다른 명령의 입력으로 전송
• 형식
commandA | commandB
| (pipe) 왼쪽에 있는 명령의 표준출력이
오른쪽에 있는 명령의 표준입력으로
사용됨
$ who > temp_file
$ wc -1 < temp_file
$ rm temp_file
$ who | wc -l
pipe
command A
stderr
예제:
stdout
stdin
stdin
command B
command C
stderr
stdout
$ ps -ef | more
$ ls | more
$ ls | sort -r | more
* command B 는 filter 이어야 함.
stderr
stdout
pipe & redirection
stdin
stdin
stdin
command A
command B
command C
stderr
예제:
stdout
stderr
stdout
stderr
stdout
$ 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
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
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 은 무시 (주석문 처리등에 유용)
• 예
$ date
Wed Mar 31 10:51:18 JST 1999
$ date | cut -c 1-3
Wed
$ date | cut -d " " -f 1-3
Wed Mar 31
tr
• 형식
tr [-s] [string1 [string2] ]
stdin으로 들어온 characters을 변환하여 stdout 으로 출력
tr [-d] [string1 [string2] ]
-s
연속하여 나오는 characters 를 single character 로 변환
-d
character 를 삭제함
• 예
$ cat samplefile
This is sample file.
$ cat samplefile | tr [a-z] [A-Z]
THIS IS SAMPLE FILE.
$ date
Wed 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
find - 형식
• 형식
find start_dir expressions actions
start_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
-exec
-ok
일치하는 항목을 찾았을 때 수행할 작업 명시
찾은 파일을 화면에 출력한다.
찾은 파일을 long format 으로 출력한다.
찾은 파일들을 exec 뒤의 명령에 하나씩 할당한다.
뒤의 명령을 실행하기 전에 사용자에게 질문한다.
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 {} \;
sed - stream editor
• 형식
file(stdin)에서 한행씩 읽어서 script 를 수행시킨
결과를 stdout 으로 출력한다.
sed [-n] [-e script] ... [-f script_file] ... [file ...]
-n
stdout 으로 출력을 내보내지 않는다.
-e
script 가 여러개인 경우 사용
-f script_file
script 가 저장된 파일 이용
sed [-n] script [file ...]
• 예
$ 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’
awk - Pattern-directed scanning and processing language
• 형식
awk script [filename …]
awk -f script_file [filename …]
파일(들)을 입력으로 받아 script 를 수행함.
저장된 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.txt
10 20 30 40 50
60 70 80 90 100
$ awk ‘{print $1+$2+$3}’ data.txt
60
210
awk - Pattern-directed scanning and processing language
• 형식
awk script [filename …]
awk -f script_file [filename …]
파일(들)을 입력으로 받아 script 를 수행함.
저장된 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.txt
10 20 30 40 50
60 70 80 90 100
$ awk ‘{print $1+$2+$3}’ data.txt
60
210
Shell II Lab
Shell II Lab (계속)
6. Process Control
Process Control
ps 명령어
• 형식
ps [-ef]
프로세스 상태를 표시한다.
-e 시스템에서 실행중인 모든 프로세스 정보 표시
-f 프로세스 상태의 전체 목록 표시
• 예
$ ps -ef
UID PID
root
0
root
1
user3 3677
user3 3714
user3 3713
PPID
0
0
3676
3677
3677
C STIME TTY TIME
0 Mar 23 ?
0:19
0 Mar 23 ?
0:00
0 23:01:16 ttyp1 0:00
0 23:03:35 ttyp1 0:00
5 23:03:35 ttyp1 0:00
COMMAND
swapper
init
ksh
grep user3
ps -ef
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
Putting Jobs In Background/Foreground
•
•
jobs
<Ctrl>+Z
•
•
fg [pid] or [%number]
bg [pid] or [%number]
현재 수행중인 Job 표시
현재 Foreground 로 수행되고 있는 Job 을 일시 중
지(suspend)시킴
해당 프로세스를 Foreground 로 수행시킴
해당 Job Number를 Background 로 수행시킴
$ while_infinite &
[1] 18817
$ jobs
[1] + Running
while_infinite &
$ fg 18817
while_infinite
<Ctrl> + Z
[1] + Stopped
while_infinite &
$ bg
[1] while_infinite &
nohup 명령어
• 형식
nohup command &
명령어가 logout 에 영향을 받지 않도록 함
• 예
$ nohup while_infinite &
[1] 18754
Sending output to nohup.out
$ exit
logout
Connection closed.
login: user3
Password:
ps -ef | grep while
user3 18754 1 169 09:19:40 ?
0:59 sh ./while_infinite
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
[1] - Terminated
$ kill -s KILL 19200
[2] + Killed
$ kill -9 0
Connection closed.
# kill -S TERM 19198 = kill -1
while_infinite &
until_infinite &
Process Control Lab
7. Shell Programming I
소개
기본
Branch
Loop
Shell Program
• UNIX 명령어를 담고 있는 Regular 파일로, UNIX에서 제공되는 다른 명
령어들처럼 실행시킬수 있다.
• File Permission 은 “r”, “x”를 포함해야 한다.
• 실행방법
$ filename
<Return>
$ ksh filename <Return>
$ ksh -x filename <Return>
“x” permission 이 있는 경우
“x” permission 이 없는 경우
쉘프로그램의 각 명령을 실행전에 표시
입력오류 등을 찾을때 유용하다.
• Shell Program 에서 할 수 있는 일들
변수 지정
명령줄에서 인수를 받아들임
대화식 입력을 받아 들임
검사 (조건 Check)/ 분기 (Branch)/ 루프 (Loop)
간단한 Shell Program 예제
$ cat myprog
#this is the program myprog
date
ls -F
$ chmod +x myprog
$ myprog
$ myprog
$
ksh
ksh
PID=1324
myprog
#
date
ls -F
date
ls
PID=1361
PID=1362
PID=1350
Shell Program 으로 데이터 전달하기
$ color=lavender
$ cat color1
echo You are now running program: color1
echo 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
$ color1
You are now running program: color1
the value of the variable color is:
$ export color
$ color1
You are now running program: color1
the value of the variable color is: lavender
Shell Program의 Argument
• Command Line
$ sh_program arg1 arg2 … argN
$0
$1
$2 … $N
• 예
$ cat color3
echo You are now running program: $0
echo The value of command line argument \#1 is: $1
echo The value of command line argument \#2 is: $2
$ chmod +x color3
$ color3 red green
You are now running program: color3
The value of command line argument #1 is: red
The value of command line argument #2 is: green
Shell Program의 Argument (Sample)
$ cat my_install
echo $0 will install $1 to your bin directory
chmod +x $1
mv $1 $HOME/bin
echo Installation of $1 is complete!
$ chmod +x my_install
$ pwd
/home/user3
$ mkdir bin
$ my_install color3
my_install will install color3 to your bin directory
Installation of color3 is complete!
$ ls -l $HOME/bin
-rwxrwxrwx 1 user3
class
139 Mar 29 11:58 color3
특수한 Shell Variables
• 특수 Shell Variable
#
*
Command Line Arguements의 수
모든 Command Line Arguments
• 예
$ cat color4
echo There are $# command line arguments
echo They are $*
echo The first command line argument is $1
$ chmod +x color4
$ color4 red green yellow blue
There are 4 command line arguments
They are red green yellow blue
The first command line argument is red
특수한 Shell Variables (Sample)
$ cat my_install2
echo $0 will install $# files to your bin directory
echo The files to be installed are: $*
chmod +x $*
mv $* $HOME/bin
echo Installation is complete!
$ chmod +x my_install2
$ my_install2 color1 color4
my_install2 will install 2 files to your bin directory
The files to be installed are: color1 color4
Installation is complete!
$ ls -l $HOME/bin
-rwxrwxrwx 1 user3
-rwxrwxrwx 1 user3
class
class
89 Mar 29 11:53 color1
101 Mar 29 12:21 color4
Shift 명령어
• 형식
shift [n]
명령줄 인수를 n 개만큼 왼쪽으로 이동 (n 생략시 1)
• 예
$ cat color5
orig_args=$*
echo There are $# command line arguments; echo They are $*
echo Shifting two arguments; shift 2
echo There are $# command line arguments; echo They are $*
$ color5 red green yellow blue orange
There are 5 command line arguments
They are red green yellow blue orange
Shifting two arguments
There are 3 command line arguments
They are yellow blue orange
Read 명령어
• 형식
read variable [variable …]
사용자로부터 입력을 받아들임
• 예
$ cat color6
echo This program prompts for user input
echo "Please enter your favorite two colors -> \c"
read color_a color_b
echo The colors you entered are : [$color_a] [$color_b]
$ color6
This program prompts for user input
Please enter your favoriate two colors => red blue
The colors you entered are : [red] [blue]
$ color6
This program prompts for user input
Please enter your favoriate two colors -> red blue white
The colors you entered are : [red] [blue white]
Read 명령어 (Sample)
$ cat my_install3
echo $0 will install files to your bin directory
echo "Enter the names of the files -> \c"
read filenames
chmod +x $filenames
mv $filenames $HOME/bin
echo Installation is complete!
$ my_install3
my_install3 will install files to your bin directory
Enter the names of the files -> f1 f2
Installation is complete!
$ ls -l $HOME/bin
-rwxr-xr-x 1 user3
-rwxr-xr-x 1 user3
class
class
32 Mar 26 22:08 f1
52 Mar 26 22:09 f2
Shell 함수 만들기
• 형식
function funct_name {shell_script}
or
funct_name ( ) {shell_script}
• 예
$ function install
>{
>
echo Install file: $1
>
chmod +x $1
>
mv $1 $HOME/bin
>
echo Install complete
>}
$ install myfile
$ install f3
Install file: f3
Install complete
or
$ install (){
>
echo Install file: $1
>
chmod +x $1
>
mv $1 $HOME/bin
>
echo Install complete
>}
$ install myfile
$ install f3
Install file: f3
Install complete
Return Code
• shell variable ? : holds the return code of the last command
executed
0
non-zero
command completed without error (true)
command termiated with error (false)
• 예
$ true
$ echo $?
0
$ ls
..
$ echo $?
0
$ echo $?
0
$ false
$ echo $?
1
$ cp
Usage: cp [-f|-i] [-p] [-e warn|force|ignore]
$ echo $?
1
$ echo $?
0
Test 명령어
• 형식
test expresssion
[ expression ]
evalutation결과
true
false
expression 을 evaluate 하고 return code 를 설정함
return code
0
non-zero (commonly 1)
• Test 명령어는 다음의 조건을 평가할 수 있다.
• Integer
• Strings
• File
Test 명령어 - 수치 테스트
• 형식
[ number1 relation number2 ]
relations:
-lt
-le
-gt
-ge
-eq
-ne
숫자들을 relation 에 대해 비교함
Less than
Less than or equal to
Greater than
Greater than or equal to
Equal to
Not equal to
• 예 (assume X=3)
$ [ $X -lt 7 ]
$ echo $?
0
$ [ $X -gt 7 ]
$ echo $?
1
Test 명령어 - 문자열테스트
• 형식
[ string1 = string2]
[ string1 != string2]
[ string ]
[ -z string ]
[ -n string ]
같은 문자열인지를 결정
다른 문자열인지를 결정
문자열의 길이가 0 이면 참
“
문자열의 길이가 0이 아니면 참
• 예
$ X=abc
$ [ “$X” = “abc” ]
$ echo $?
0
$ X=abc
$ [ “$X” != “abc” ]
$ echo $?
1
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
$ test -f color5; echo $?
0
$ test -d color5; echo $?
1
168 Mar 29 13:37 color5
Test 명령어 - 기타 연산자
• 형식
-o
-a
!
\( \)
OR
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” \) ]
If 구문
• 형식
if list A
then
list B
fi
1. list A를 수행한다.
2. 수행 결과가 참이면 list B를
수행한다.
or
if list A
then
list B
else
list C
fi
1. list A를 수행한다.
2. 수행 결과가 참이면 list B를 수행하고
거짓이면 list C 를 수행한다.
• 예제
if test -s funfile
then
echo funfile exists
fi
if [ $X -lt 10 ]
then
echo X is less than 10
else
echo X is not less than 10
fi
Case 구문 - Multi-direcitonal branching
• 형식
case word in
pattern1)
list A ;;
pattern2)
list B ;;
patternN)
list N ;;
*)
list C ;;
esac
word가 pattern1과 같으면 list A를 수행,
pattern2과 같으면 list B를 수행, …,
같은 것이 없으면 list C 를 수행한다.
• 예제
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
case 구문 - sample
$ cat menu_with_case
echo
COMMAND MEMU
echo d to display time and date
echo w to display all login user
echo l to display the contents of current dir
echo ""
echo "Please enter your choice : \c"
read choice
case $choice in
[dD]*) date ;;
[wW]*) who ;;
[lL]*) ls ;;
*) echo Invalide choice ;;
esac
Arithmetic Evaluation
• 형식
let expression
(( expression ))
• 예
$ x=10
$ y=2
$ let x=x+2
$ echo $x
12
$ (( x=x/(y+2) ))
$ echo $x
3
산술식을 계산함
while 구문
• 형식
while list A
do
list B
done
조건(list A)가 참인 동안 list B를 계속 수행한다.
• 예
$ cat test_while
X=1
while (( X <= 10 ))
do
echo X is $X; let X=X+1
done
$ test_while
X is 1
X is 2
..
X is 10
until 구문
• 형식
until list A
do
list B
done
조건(list A)가 참일 때까지 list B를 계속 수행한다.
• 예
$ cat test_until
X=1
while (( X > 10 ))
do
echo X is $X; let X=X+1
done
$ test_until
X is 1
X is 2
..
X is 10
for 구문
• 형식
for variable in list A
do
list B
done
variable 에 list A의 값들이 차례로
할당되면서list B 를 수행한다.
• 예
$ cat test_for
for X in 1 2 3 4 5
do
echo "2 * $X is \c"
let X=X*2; echo $X
done
$ ksh test_for
2 * 1 is 2
2 * 2 is 4
2 * 3 is 6
2 * 4 is 8
2 * 5 is 10
break, continue, exit 명령어
• break
• continue
• exit [n]
• 예제
루프를 완전히 벗어난다.
루프의 현재 반복을 멈추고 다음 반복으로 들어간다.
쉘프로그램의 수행을 정지시키고 n (생략시 마지막
명령문 수행 결과)를 return code 로 반환한다.
$ cat test_control
while true
do
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
Shell Programming I Lab
8. Shell Programming - Signal 과 trap
Signal
Trap
Signal 이란?
• Signal
특정 Event 가 발생했을 때 프로세스에게 보내지는 신호 (flag)
• Signal 과 Event
이름
번호 Event
Shell 이 종료됨
EXIT
HUP
1
Hangup. 제어단말기의 연결이 끊어졌을 때.
Logout 시
Backgroud 로 돌고 있는 프로세스에게 보내진다.
INT
QUIT
KILL
TERM
2
3
9
15
Interrupt 가 발생함. <Ctrl> + C.
quit. <Ctrl>+\. Core 파일을 생성
kill
Software Termination
• kill 명령어: 프로세스에게 특정 시그널을 보냄
kill [-s signal ] pid
default 는 TERM 시그널을 보냄
Trap 이란?
• trap:
프로세스에게 전송된 시그널을 포착함
수신된 신호의 종류에 따라 어떤 활동을 수행함
• 예
프로그램 종료시 임시파일들을 모두 삭제한다.
중요한 작업시 INT 시그널을 무시한다.
Trap 명령어 - Catch Signal
• 형식
trap ‘commands’ signal [signal … ]
signal 을 받았을 때
commands 를 수행함
• 예
$ more mytrap
trap 'echo bye; exit' INT QUIT TERM
while true
do
echo hello
sleep 1
done
$ mytrap
hello
hello
…
<== <Ctrl> + C
bye
$
Trap 명령어 - Sample
• trap 을 사용한 쉘 명령 내역 파일 정리
$ trap 'mv $HOME/.sh_history $HOME/.sh_hist.old' EXIT
$ ls ~/.sh*
/home/user3/.sh_history
$ exit
login: user3
Password:
$ 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 .profile
trap “$HOME/.logout” EXIT
…
===> $HOME/.logout 에 로그아웃시 실행할 명령어들을 기록
Trap 명령어 - Ignore Signal
• 형식
trap ‘’ signal [signal … ]
signal 을 받았을 때 아무일도 하지 않음
(signal 을 무시함)
• 예
$ more mytrap2
trap '' INT
while true
do
echo hello
sleep 1
done
$ mytrap2
hello
hello
<=== <Ctrl> + C : ignored
hello
hello
<=== <Ctrl> + \
$
Trap의 위치
–
종료전에 특정일을 수행하는 경우
• 전체 프로세스의 실행에 대해 사용될수 있도록 프로그램의 시작에 있어
야 한다.
• 예) 종료시 임시파일을 지우는 경우
trap ‘ rm /tmp/tmpfile; exit’ INT QUIT TERM
– 중요한 일을 수행하는 동안 Signal 을 무시하려는 경우
trap ‘’ INT QUIT TERM
do_critical_things
trap INT QUIT TERM
Shell Programming II Lab
9. 시스템 관리 기초
사용자 관리
장치파일
System Startup & Shutdown
Backup & Recovery
Job Scheduling
사용자 관리
• 사용자와 그룹의 추가/삭제
• 관련 파일
/etc/passwd
/etc/group
사용자 login 정보
그룹 정보
/etc/passwd
• 예
root::0:3::/:/sbin/sh
daemon:*:1:5::/:/sbin/sh
user2:N8aQNxXWCNcJg:602:600:,,,:/home/user2:/usr/bin/ksh
user3: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
/etc/passwd
• 예
root::0:3::/:/sbin/sh
daemon:*:1:5::/:/sbin/sh
user2:N8aQNxXWCNcJg:602:600:,,,:/home/user2:/usr/bin/ksh
user3: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
/etc/group
• 예
root::0:root
other::1:root,hpdb
class::600:user1,user2,user3
student::500:user3
• 형식 확인시 /usr/sbin/grpck 사용
class: :600:user1,user2,user3
group_name
password
group_list
group ID
사용자 생성
1. /etc/passwd 에 해당 user 정보 삽입
2. /etc/group 에 해당 user 추가
3. 사용자 Home directory 생성
$ mkdir /home/loginame
4. 사용자 Home directory permission 변경
$ chmod 755 /home/loginname
5. 필요한 파일 복사
$ cp /etc/skel/.[!.]* /home/loginname
6. Home directory 소유자/그룹 변경
$ chown -R loginname:group /home/loginname
사용자 생성 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
Device File (장치파일, 특수파일)
Device
File
UNIX Command
Applications
Kernel
디스크
디스크
테이프
테이프
디스크
모니터
peripheral devices
Listing Device Files
• Listing Device with ls -l
brw-r----brw-r----crw-r----crw-r----crwxrwxrwx
crwxrwxrwx
1 root
1 root
1 root
1 root
1 bin
1 bin
Device File 유형
sys
sys
sys
sys
bin
bin
31 0x00f000 Jun 10 1996 /dev/dsk/c0t15d0
31 0x006000 Mar 22 15:26 /dev/dsk/c0t6d0
188 0x00f000 Jun 10 1996 /dev/rdsk/c0t15d0
188 0x006000 Mar 23 14:08 /dev/rdsk/c0t6d0
193 0x000000 Jun 10 1996 /dev/tty0p0
193 0x000100 Jun 10 1996 /dev/tty0p1
major #
minor #
Device File 이름
/dev 디렉토리 구조
/
dev
dev
rdsk
Disk Devices
rmt
ttyxpy
ttydxpy
Tape Devices
Terminals
Modems
Disk, Tape Device File Name
System
Solaris
HP-UX
IRIX
SunOS
OSF/1
BSD1
•
SCSIDisk
Tape
/dev/rdisk/c?t?d?s? /dev/rmt/?
/dev/rdisk/c?t?d?s? /dev/rmt/?m
/dev/rdisk/dks?d?s? /dev/tape
/dev/rsd??
/dev/rmt?
/dev/rrz?
/dev/rmt?{lmh}
/dev/sd??
/dev/rmt?
Non-rewinding tape
/dev/rmt/?n
/dev/rmt/?mn
/dev/rmt/nrtape
/dev/nrmt?
/dev/nrmt?{lmh}
/dev/nrmt?
위의 표에서 'r'은 disk를 raw mode로 사용할 경우에 사용하는 이름이고 '?'는 해당 disk나
partition의 숫자를 나타낸다.
Instance number of the
interface card
SCSI target address
Device number
Device Dependent
Information
c#t#d#[other]
UNIX Operating State
Shutdown -h
Single-user Mode
reboot -h
Halt State
power-off
reboot
shutdown -r
shutdown
Multi-user Mode
Power-Off
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를 실행시킨다.
압축 Utility
• tar: 여러 개의 파일을 하나의 지정된 파일로 묶음
$ tar cvf <만들 파일이름>.tar <묶고자하는 파일이름>
여러파일을 하나로 묶음
$ tar xvf <묶여있는 파일이름>.tar
묶여있는 파일을 풀음
$ tar tvf <묶여있는 파일이름>.tar
묶여있는 파일 목록 확인
• compress & uncompress: 파일 압축/압축 풀기
$ compress filename
$ uncompress filename
filename 이 filename.Z으로 압축됨
압축된 파일 filename.Z 가 filename으로
압축이 풀림
• gzip : 파일 압축/압축 풀기
$ gzip filename
$ gzip -d filename
filename 이 filename.gz으로 압축됨
압축된 파일 filename.gz 이 filename 으
로 압축이 풀림
압축 Utility
• tar: 여러 개의 파일을 하나의 지정된 파일로 묶음
$ tar cvf <만들 파일이름>.tar <묶고자하는 파일이름>
여러파일을 하나로 묶음
$ tar xvf <묶여있는 파일이름>.tar
묶여있는 파일을 풀음
$ tar tvf <묶여있는 파일이름>.tar
묶여있는 파일 목록 확인
• compress & uncompress: 파일 압축/압축 풀기
$ compress filename
$ uncompress filename
filename 이 filename.Z으로 압축됨
압축된 파일 filename.Z 가 filename으로
압축이 풀림
• gzip : 파일 압축/압축 풀기
$ gzip filename
$ gzip -d filename
filename 이 filename.gz으로 압축됨
압축된 파일 filename.gz 이 filename 으
로 압축이 풀림
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
$ tar xvf /dev/rmt/0m
$ tar tvf /dev/rmt/0m
*
현재 디렉토리의 내용을 Tape에 저장
Tape의 기존 데이터를 덮어쓴다.
Tape 내용을 디스크에 restore
Tape에 저장된 파일 목록 확인
cron & crontab
• cron Daemon
명령을 특정한 시간 간격으로 수행
• crontab
cron이 참조하는 table의 생성
사용법
crontab [filename] 이미 만들어져 있는 file의 등록
crontab -e
editer상에서 화일을 작성
crontab -l
사용자의 crontab 화일을 보여줌
crontab -r
사용자의 crontab 화일을 제거
cronfile 형식
•
•
스페이스나 탭으로 분리된 6개의 필드로 구성된다.
첫번째에서 다섯번째 까지는 각각 시간, 날짜, 요일을 표시하고 여섯번째 필드는
수행될 명령어를 표시한다.
•
예) crontab -l
# min hour date month day
# 0-59 0-23 1-31 1-12 0-6
0
*
*
*
*
0
5
*
*
1-5
15
4
*
*
*
0
6
*
*
command
/usr/bin/date > /dev/console
/usr/bin/who | /usr/bin/lp
find /var/preserve/ -mtime +7 -exec
rm -f {} \; > /dev/null 2>&1
2,4,6 tar cvf /dev/rmt/0m ./HOME/* >
/dev/null 2>&1
참고문헌