UNIX 1 UNIX 2 3 vi 4 Shell
- Slides: 154
UNIX 기초
목차 1. UNIX 시스템 소개 2. 파일 관리 3. vi 편집기 기초 4. Shell I 5. Shell II 6. Process Control 7. Shell Programming I 8. Shell Programming II 9. 시스템 관리 기초
UNIX 소개 운영체제 Disks Memory Users Programs Customers Operating System CPU Network Printers Resources UNIX 운영체제 시분할 방식의 다중 작업 (Multi-tasking) 다중 사용자 환경 (Multi-user) 높은 이식성과 호환성
Logging In and Out login: user 1 Password: $ date $ other commands $ exit or <Ctrl>+d Login message Do work Log out
Command Line 형식 • 형식: $ command [-option] [argument] • 예: $ date Wed Mar 31 20: 33: 32 JST 1999 $ ls dira dirb f 1 f 2 prog 1 prog 2 $ ls -F dira/ dirb/ f 1 f 2 prog 1* prog 2*
Online 매뉴얼 • 형식: man [-X] command X: Manual Page Section number • Section 번호와 내용 (HP-UX) 1: User Commands 1 m: 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(user 1) gid=600(class) • w 시스템 botting 시간, load, login 사용자 정보(작업)표시 $w 9: 00 pm 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: 46 pm 129: 04 -sh user 3 pts/0 2: 59 pm w • who root user 3 현재 login 한 사용자 정보 표시 console pts/0 • who am i user 3 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 user 1 Old password: New password: Re-enter new password
기본 명령어 (III) • hostname 시스템의 이름을 표시 $ hostname ich 01 • uname 시스템에 탑재된 운영체제에 관한 정보 표시 $ uname -a HP-UX ich 01 B. 10. 20 U 9000/869 1426594321 unlimited-user license • echo 메시지 표시 $ echo how are you • banner 큰 글자로 표시 $ banner hi! # # #### # # ### ## ###
기본 명령어 (IV) • write login 하고 있는 user의 terminal 로 메시지를 보냄 $ write user 2 [tty 0 p 4] Hi <Return> Nice to meet you! <Return> <Ctrl>+d • mesg 메시지 수신 허용/불가 설정 $ mesg is y $ mesg n $ mesg is n • mail 사용 user 1 에게 메일을 보냄 $ mail user 1 see you again <Ctrl> + d $ $ mail 받은 메일을 읽음
File System Hierarchy
File System 기본 명령어 II • pwd 현재 작업 디렉토리를 표시(Present Working Directory) $ pwd /home/user 1 • cd 디렉토리 변경 (Change Directory) $ pwd /home/user 3 $ cd memo; pwd /home/user 3/memo $ cd. . /; pwd /home $ cd /tmp; pwd /tmp $ cd; pwd /home/user 3
File System 기본 명령어 III • find 파일을 찾음 형식: find start_dir -name filename start_dir 에서 시작해서 파일 이름이 filename 인 파일을 찾는다. start_dir 경로이름 목록. 지정 경로로부터 재귀적으로 검색 예 $ find. -name. profile. /. profile $ find / -name f 1 /home/user 3/memo/f 1 /home/user 3/f 1 $ find. -name core
File System 기본 명령어 IV • mkdir, rmdir 디렉토리를 만듦, 디렉토리를 삭제 형식: mkdir [-p] dir_pathname(s) 디렉토리를 만듦 -p : 중간디렉토리가 없는 경우 생성 rmdir dir_pathname(s) 디렉토리를 삭제함 예 $ lsf f 1 f 2* 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 특성 $ ls -l -rw-r--r-1 user 3 -rwxr-xr-x 1 user 3 drwxrwxrwx 2 user 3 파일유형 링크수 Permissions 소유자 class 44 Mar 26 16: 21 f 1 67 Mar 26 16: 22 f 2 1024 Mar 26 16: 12 memo 그룹 크기 Time Stamp 이름
cat 명령어 • 형식 cat file [file …] • 예 $ cat f 1 Test file! $ cat f 2 Test file, too! $ cat f 1 f 2 Test file! Test file, too! $ 파일의 내용을 표시함 • 간단한 파일만들기 $ cat > filename <Enter> This is test file …. . <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 -f [-n number ] filename 파일의 처음 number 줄을 표시함 (default 10) 파일의 마지막 number 줄을 표시함 (default 10) -f: Follow Option. • 예 $ head -n 10 longfile $ tail -f longfile …. . <Ctrl> + C $ ( = $ head longfile ) ( = $ tail longfile )
mv 명령어 • 형식 mv [-i] file 1 new_file mv [-i] file [file …] dest_dir mv [-i] dir [dir …] dest_dir -i 대화식 option. • 예 $ ls -F f 1 f 2* memo/ note remind $ mv f 1 file 1 $ ls -F file 1 f 2* memo/ note remind $ mv f 2 memo/file 2 $ ls -F file 1 memo/ note remind $ ls -F memo file 2* 파일의 이름을 바꿈 파일(들)을 다른 디렉토리 밑으로 이동 디렉토리 이름을 바꿈 또는 다른 디렉토리 밑 으로 이동
rm 명령어 • 형식 rm [-if] filename [filename. . ] rm -r [-if] filename [filename. . ] • 예 $ ls -F f 1 f 2* fruits/ memo/ $ rm f 1; $ ls -F f 2* fruits/ memo/ $ rm -i f 2: ? (y/n) y $ rm fruits rm: fruits directory $ rm -r fruits 파일을 삭제함 디렉토리를 삭제함
diff 명령어 • 형식 diff [-i] file 1 file 2 파일의 내용을 비교함 -i : 대소문자를 무시함 • 예 $ cat fruit 1 I like fruits apple orange $ diff fruit 1 fruit 2 3 a 4, 5 > grapes > melon $ cat fruit 2 I like fruits apple orange grapes melon $ cat fruit 3 I like fruits very much apple strawberry $ diff fruit 1 fruit 3 1 c 1 < I like fruits --> I like fruits very much 3 c 3 < orange --> strawberry
ln 명령어 • 형식 ln file new_file ln file [file …] dest_dir Link to a file Link files to a directory • 예 $ ls -l f 1 -rw-r--r-- 1 user 3 class 44 Mar 26 16: 21 f 1 $ ln f 1 /home/user 2/f 1. link $ ls -l f 1 -rw-r--r-- 2 user 3 class 44 Mar 26 16: 21 f 1 $ ls -l /home/user 2 -rw-r--r-- 2 user 3 class 44 Mar 26 16: 21 f 1. link $ ls -i f 1 /home/user 2/f 1. link 97852 f 1
ln 명령어 (Hard Link) • 형식 ln file new_file Link to a file ln file [file …] dest_dir Link files to a directory • 예 $ ls -l f 1 -rw-r--r-- 1 user 3 class 44 Mar 26 16: 21 f 1 $ ln f 1 /home/user 2/f 1. link $ ls -l f 1 -rw-r--r-- 2 user 3 class 44 Mar 26 16: 21 f 1 $ ls -l /home/user 2 -rw-r--r-- 2 user 3 class 44 Mar 26 16: 21 f 1. link $ ls -i f 1 /home/user 2/f 1. link 97852 f 1
파일 허가와 접근 (예) $ ls -l - rw- r-- 1 user 3 - rwxr-x 1 user 3 drwxr-x 2 user 3 사용자 그룹 기타 소유자 class 그룹 32 Mar 26 22: 08 f 1 52 Mar 26 22: 09 f 2 1024 Mar 26 21: 07 memo
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-rw. New Permission: rwxr-xr-x rwx $ chmod u+x, g+x, o+x file or $ chmod +x file group other r-r-r-x or $ chmod 755 file
umask - 파일 모드 작성 마스크값 설정 • 형식 umask 현재 파일모드 작성 마스크 값 인쇄 파일모드 작성 마스크 값 설정 mode • 예제 default permissions: set default permissions: $ 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 f 1 -rw-r--r-- 1 user 3 class -rwxr-xr-x 1 user 3 class $ chgrp users f 1 $ ls -l f 1 -rw-r--r-- 1 user 3 users $ chown user 2 f 1 $ ls -l f 1 -rw-r--r-- 1 user 2 users $ chown user 3: users f 2 $ ls -l f 2 -rwxr-xr-x 1 user 3 users 32 Mar 26 22: 08 f 1 52 Mar 26 22: 09 f 2
su - Switch User ID • 형식 su user_name su user ID 와 group ID 를 바꿈 사용자를 root 로 전환 • 예제 $ id uid=603(user 3) gid=600(class) $ su user 2 Password: $ id uid=602(user 2) gid=600(class). . . $ exit or <Ctrl+d> $ id uid=603(user 3) gid=600(class)
telnet • 형식 telnet hostname telnet ip_address hostname 으로 원격연결한다. ip_address로 원격연결한다. • 예제 $ telnet alpha 2 or telnet 105. 20. 19. 210 Trying. . . Connected to alpha 2. Escape character is '^]'. Local flow control on Telnet TERMINAL-SPEED option ON HP-UX alpha 2 B. 10. 20 C 9000/887 (ttyp 4) login: yuhwa Password: [alpha 2: /user 3/yuhwa]
rlogin • 형식 rlogin hostname [-l username] hostname 으로 원격접속한다. -l username: 해당 username으로 원격접속한다. default 는 지역사용자 id • 예제 $ rlogin alpha 2 -l yuhwa Password: [alpha 2: /user 3/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 이라는 호스트에 연결을 시도 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
vi 시작하기 • 형식 $ vi [filename] $ vi -R filename (cf. view) $ vi -r [filename] 기존파일 또는 새로운 파일을 편집함 파일을 Read Only 상태로 열음 재난을 당한 파일 복구 • 예 $ vi sample_file Memory Disk sample_file $ vi sample_file Terminal Display xxxxxxx xxx….
vi modes • Command Mode • Input Mode • Last Line Mode (ex) : keystrokes 을 command 로 해석 : keystrokes 시 파일에 입력됨 : ex command를 수행 : / ? return Command Mode a i o A I O esc Input Mode
4. Shell I 개념 기본 Command
Shell 개념 Users environment settings Shell command execution Kernel environment settings pipelines Hardware variable assignment I/O redirection variable substitution filename generation command substitution
Shell 종류
Korn Shell 특징 • • • Command Alias File name completion Command History Re-entering command Recalling command Command line editing
Aliasing • 형식 alias name=string 현재 정의된 모든 alias 를 표시 name 에 설정된 alias 표시 string 을 name 이란 이름의 alias 로 설정 • 예제 $ alias dir='ls -F' $ dir f 1 f 2* f 3 memo/ test/ $ alias dir=ls -F $ alias copy=cp $ alias del='rm -i'
File Name Completion $ ls -l -rw-r--r-- 1 user 3 class -rwxr-xr-x 1 user 3 class -rw-rw-rw- 1 user 3 class $ cat sa <esc> $ cat sample. txt <Return>. . . $ cat f <esc> = 1) f 1 2) f 2 3) f 3 $ cat f <a>1. . . 32 Mar 26 22: 08 f 1 52 Mar 26 22: 09 f 2 32 Mar 27 19: 47 f 3 23 Mar 27 22: 05 sample. txt
사용자 환경 • 환경변수 HOME 홈 디렉토리에 대한 경로 이름 PATH 명령을 찾아보는 곳의 목록 TERM, COLUMN, LINES 사용중인 단말기 설명 LOGNAME 로그인하는데 사용한 사용자 이름 HISTFILE 이전 명령어 저장 EDITOR Command Line Editor 저장 • 환경 점검 $ env PATH=/usr/bin: /usr/contrib/bin: / COLUMNS=80 EDITOR=vi LOGNAME=user 3 HOME=/home/user 3 TERM=ansi LINES=29
login 절차 kernel getty • 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 /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 • 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
Display Variable Values $ echo $HOME /home/user 3 $ env PATH=/usr/bin: /usr/contrib/bin: /usr/local/bin: /home/user 3: . HOME=/home/user 3 TERM=ansi $ set PATH=/usr/bin: /usr/contrib/bin: /usr/local/bin: /home/user 3: . HOME=/home/user 3 TERM=ansi dir_name=memo/fruits file 1=this file 2=that my_ls=ls -a. FC
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/user 3: . $ dir_name=memo/fruits ; echo $dir_name memo/fruits $ ls -F $dir_name apple orange test/ $ my_ls="ls -a. FC" $ $my_ls $dir_name. / apple orange test/
Command Substitution • 형식 $(command) `command` • 예 $ pwd /home/user 3 $ curdir=$(pwd) $ echo $curdir /home/user 3 $ cd /tmp $ pwd /tmp $ cd $curdir $ pwd /home/user 3 명령을 수행시킨 결과로 대체
5. Shell II I/O Redirection Filter Pipe
stdin, stdout, stderr File Device File Descriptor stdin 0 stdout 1 stderr 2
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 user 3: p 88 g. QZp. B 3 S/Fg: 603: 600: , , , : /home/user 3: /usr/bin/ksh 1 2 3 4 5 6 7 $ sort -nt: -k 3 /etc/passwd
grep • 형식 grep [-cinv] -c -i -v -n -f -e patterns [file …] file 에서 patterns 을 찾는다. -f pattern_file [file … ] 일치하는 줄들의 수만 인쇄한다. 패턴에서 문자의 대소문자를 구분하지 않는다. 패턴이 들어있지 않은 줄만 표시 표시된 각 줄에 줄 번호를 붙임 패턴이 저장된 파일 명시 패턴이 2개 이상이 경우 사용 • 예 $ grep user /etc/passwd user 2: N 8 a. QNx. XWCNc. Jg: 602: 600: , , , : /home/user 2: /usr/bin/ksh user 3: p 88 g. QZp. B 3 S/Fg: 603: 600: , , , : /home/user 3: /usr/bin/ksh $ grep -v user /etc/passwd $ grep -i user /etc/passwd $ grep ‘^user’ /etc/passwd
pipe command A stderr 예제: stdout stdin command B command C stderr stdout $ ps -ef | more $ ls | sort -r | more * command B 는 filter 이어야 함. stderr stdout
pipe & redirection stdin command A command B command C 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 - 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] [string 1 [string 2] ] stdin으로 들어온 characters을 변환하여 stdout 으로 출력 tr [-d] [string 1 [string 2] ] -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 - Example • 예 $ find. -name. profile $ find / -name f 1 $ find. -name core -exec rm {} ; $ find / -mtime +7 $ find. -mtime -10 -ok rm {} : $ find / -size +2000 $ find / -size -1000000 c $ find. -type f -exec chmod 444 {} ; $ find. -type d -exec chmod 555 {} ;
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/' file 1 > file 1. out $ sed -e 's/abc/xyz/' -e 's/lmn/rst/' file 1> file 1. 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 user 3 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 user 3 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
6. Process Control
ps 명령어 • 형식 ps [-ef] 프로세스 상태를 표시한다. -e 시스템에서 실행중인 모든 프로세스 정보 표시 -f 프로세스 상태의 전체 목록 표시 • 예 $ ps -ef UID PID root 0 root 1 user 3 3677 user 3 3714 user 3 3713 PPID 0 0 3676 3677 C STIME TTY 0 Mar 23 ? 0 23: 01: 16 ttyp 1 0 23: 03: 35 ttyp 1 5 23: 03: 35 ttyp 1 TIME 0: 19 0: 00 COMMAND swapper init ksh grep user 3 ps -ef
Background Processing • 형식 $ command & Background로 작업을 수행한다. • 예 $ cat while_infinite while true do echo hello done $ while_infinite > test. out & [3] 18182 $ ps -f UID PPID C STIME TTY TIME COMMAND user 3 18171 17880 0 22: 08: 46 pts/3 0: 00 cat user 3 18182 17880 104 22: 10: 51 pts/3 0: 03 -ksh user 3 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: user 3 Password: ps -ef | grep while user 3 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 &
7. Shell Programming I 소개 기본 Branch Loop
간단한 Shell Program 예제 $ cat myprog #this is the program myprog date ls -F $ chmod +x myprog $ myprog
Shell Program 으로 데이터 전달하기 $ color=lavender $ cat color 1 echo You are now running program: color 1 echo the value of the variable color is: $color $ ls -l color 1 -rw-rw-rw- 1 user 3 class 89 Mar 29 11: 53 color 1 $ chmod +x color 1 $ color 1 You are now running program: color 1 the value of the variable color is: $ export color $ color 1 You are now running program: color 1 the value of the variable color is: lavender
Shell Program의 Argument • Command Line $ sh_program arg 1 arg 2 … arg. N $0 $1 $2 … $N • 예 $ cat color 3 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 color 3 $ color 3 red green You are now running program: color 3 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/user 3 $ mkdir bin $ my_install color 3 my_install will install color 3 to your bin directory Installation of color 3 is complete! $ ls -l $HOME/bin -rwxrwxrwx 1 user 3 class 139 Mar 29 11: 58 color 3
특수한 Shell Variables • 특수 Shell Variable # * Command Line Arguements의 수 모든 Command Line Arguments • 예 $ cat color 4 echo There are $# command line arguments echo They are $* echo The first command line argument is $1 $ chmod +x color 4 $ color 4 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_install 2 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_install 2 $ my_install 2 color 1 color 4 my_install 2 will install 2 files to your bin directory The files to be installed are: color 1 color 4 Installation is complete! $ ls -l $HOME/bin -rwxrwxrwx 1 user 3 class 89 Mar 29 11: 53 color 1 101 Mar 29 12: 21 color 4
Shift 명령어 • 형식 shift [n] 명령줄 인수를 n 개만큼 왼쪽으로 이동 (n 생략시 1) • 예 $ cat color 5 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 $* $ color 5 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 color 6 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] $ color 6 This program prompts for user input Please enter your favoriate two colors => red blue The colors you entered are : [red] [blue] $ color 6 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_install 3 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_install 3 will install files to your bin directory Enter the names of the files -> f 1 f 2 Installation is complete! $ ls -l $HOME/bin -rwxr-xr-x 1 user 3 class 32 Mar 26 22: 08 f 1 52 Mar 26 22: 09 f 2
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 f 3 Install file: f 3 Install complete or $ install (){ > echo Install file: $1 > chmod +x $1 > mv $1 $HOME/bin > echo Install complete >} $ install myfile $ install f 3 Install file: f 3 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 $ 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 명령어 - 수치 테스트 • 형식 [ number 1 relation number 2 ] relations: -lt -le -gt -ge -eq -ne 숫자들을 relation 에 대해 비교함 Less than or equal to Greater than or equal to Equal to Not equal to • 예 (assume X=3) $ [ $X -lt 7 ] $ echo $? 0 $ [ $X -gt 7 ] $ echo $? 1
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 pattern 1) list A ; ; pattern 2) list B ; ; pattern. N) list N ; ; *) list C ; ; esac word가 pattern 1과 같으면 list A를 수행, pattern 2과 같으면 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 [d. D]*) date ; ; [w. W]*) who ; ; [l. L]*) 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 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
8. Shell Programming - Signal 과 trap Signal Trap
Trap 명령어 - Catch Signal • 형식 trap ‘commands’ signal [signal … ] signal 을 받았을 때 commands 를 수행함 • 예 $ more mytrap 'echo bye; exit' INT QUIT TERM while true do echo hello sleep 1 done $ mytrap hello … <== <Ctrl> + C bye $
Trap 명령어 - Sample • trap 을 사용한 쉘 명령 내역 파일 정리 $ trap 'mv $HOME/. sh_history $HOME/. sh_hist. old' EXIT $ ls ~/. sh* /home/user 3/. sh_history $ exit login: user 3 Password: $ ls -l. sh* -rw------- 1 user 3 class 2694 Apr 2 18: 03. sh_hist. old -rw------- 1 user 3 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 mytrap 2 trap '' INT while true do echo hello sleep 1 done $ mytrap 2 hello<=== <Ctrl> + C : ignored hello<=== <Ctrl> + $
9. 시스템 관리 기초 사용자 관리 장치파일 System Startup & Shutdown Backup & Recovery Job Scheduling
/etc/passwd • 예 root: : 0: 3: : /: /sbin/sh daemon: *: 1: 5: : /: /sbin/sh user 2: N 8 a. QNx. XWCNc. Jg: 602: 600: , , , : /home/user 2: /usr/bin/ksh user 3: p 88 g. QZp. B 3 S/Fg: 603: 600: , , , : /home/user 3: /usr/bin/ksh • 편집시 /usr/sbin/vipw 사용 • 형식 확인시 /usr/sbin/pwck 사용 user 3: p 88 g. QZp. B 3 S/Fg: 603: 600: , , , : /home/user 3: /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 user 2: N 8 a. QNx. XWCNc. Jg: 602: 600: , , , : /home/user 2: /usr/bin/ksh user 3: p 88 g. QZp. B 3 S/Fg: 603: 600: , , , : /home/user 3: /usr/bin/ksh • 편집시 /usr/sbin/vipw 사용 • 형식 확인시 /usr/sbin/pwck 사용 user 3: p 88 g. QZp. B 3 S/Fg: 603: 600: , , , : /home/user 3: /usr/bin/ksh username password user ID group ID home directory startup program
/etc/group • 예 root: : 0: root other: : 1: root, hpdb class: : 600: user 1, user 2, user 3 student: : 500: user 3 • 형식 확인시 /usr/sbin/grpck 사용 class: : 600: user 1, user 2, user 3 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 user 1 user 2. . user 18 $ 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 (장치파일, 특수파일) UNIX Command Applications Device File Kernel 디스크 테이프 디스크 모니터 peripheral devices
Listing Device Files • Listing Device with ls -l brw-r----crw-r----crwxrwxrwx 1 root 1 bin Device File 유형 sys sys bin 31 0 x 00 f 000 Jun 10 1996 /dev/dsk/c 0 t 15 d 0 31 0 x 006000 Mar 22 15: 26 /dev/dsk/c 0 t 6 d 0 188 0 x 00 f 000 Jun 10 1996 /dev/rdsk/c 0 t 15 d 0 188 0 x 006000 Mar 23 14: 08 /dev/rdsk/c 0 t 6 d 0 193 0 x 000000 Jun 10 1996 /dev/tty 0 p 0 193 0 x 000100 Jun 10 1996 /dev/tty 0 p 1 major # minor # Device File 이름
Disk, Tape Device File Name System Solaris HP-UX IRIX Sun. OS OSF/1 BSD 1 • SCSIDisk Tape /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? {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
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/0 m $ tar xvf /dev/rmt/0 m $ tar tvf /dev/rmt/0 m * 현재 디렉토리의 내용을 Tape에 저장 Tape의 기존 데이터를 덮어쓴다. Tape 내용을 디스크에 restore Tape에 저장된 파일 목록 확인
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 * * 2, 4, 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 tar cvf /dev/rmt/0 m. /HOME/* > /dev/null 2>&1
- Germinal disc in egg
- Firmness of the yolk and freedom from yolk defects
- Shell interpretive cycle
- Shell interpretive cycle
- Exchange proxy shell
- 2-4 pass shell and tube heat exchanger
- Valence shell
- Tube inserts for heat exchangers
- Asp webshell
- Agv shell
- Shell slide
- Heat exchanger cost estimation
- Adb commands
- In shell and tube surface condenser
- Silicon shell
- Counting orbitals
- Insertion sort loop invariant
- Shell hsse golden rules
- In shell and tube surface condenser
- Shell model human factors
- Silicon shell
- Heavier than
- Brunei shell petroleum
- Is moss living or non-living
- Shell model of nucleus
- Orthoceratitic
- Shell model of nucleus
- Shell trailer hire
- Shell and tube heat exchanger in oil refinery
- Tarlochan singh dhillon
- Tongue twister sea shells
- Cross counter flow heat exchanger
- David hone shell
- Stormed at with shot and shell meaning
- Fun shell scripts
- Electron shell capacities
- Gramatický větný vzorec
- Conispiral shell
- Dr graham glass
- Command line arguments in unix
- Monika shell
- Electrostatic force
- Subshell orbital
- A ten inch fireworks shell is fired
- Shell journey management plan template
- Tema class c
- Modello shell fattore umano
- Shell process safety
- Neon neutroner
- Elongday
- Type of structure
- Valence shell electron pair repulsion
- Coral energy shell
- Equivalent diameter shell tube heat exchanger
- Shell auto gas
- How many orbitals are there in the third shell of ytterbium
- Thumbelina walnut shell
- A shell and tube heat exchanger
- Shell method calculus formula
- Cylindrical shells formula
- Shell international petroleum company
- Arena shell para fundición
- Shell hsse goldene regeln
- Parallel heat exchanger
- Types of recuperator
- Shell energy europe bv
- Shell script dialog
- Anti penultimate shell
- Hazop of heat exchanger
- Insertion sort divide and conquer
- Unit 5 clipart
- Linux diff komutu
- Sql server shell
- What is shell
- Jess java
- Info
- A double pipe parallel flow heat exchanger
- Internal shell squid
- Slidetodoc.com
- Shell and tube heat exchanger in food industry
- Shell and
- Valence shell electron pair repulsion
- Shell keep castles advantages and disadvantages
- Elements of condensing plant
- Positive approach llc
- Cmu shell lab
- Bash shell exercises
- Periodic table group practice problems
- Dtlm heat exchanger
- Shell cube in data mining
- Al2o3 ionic bonding
- Small shell and tube heat exchanger
- Shell side reynolds number
- Read command is shell's internal tool
- A ten inch fireworks shell is fired
- Shell journey management plan template
- Chronic unease shell
- Shell
- Shell
- Lithium fluoride bohr diagram
- Tücsi a galaktikus
- Shell science lab challenge
- Full valence shell period 3
- Cylindrical shells method
- Dylan shell tamu
- Bash shell
- Magnesium atomic number
- Ssh secure shell wiki
- Fourier shell correlation
- Step up transformer construction
- Complete outer shells periodic table
- Shell command interpreter
- 5 characteristics of shellfish
- Shell and tube type condenser
- Shell and tube heat exchanger sizing
- Shell cube in data mining
- U shell
- Heraldic colors
- Floating head heat exchanger supplier
- Orbital filling sequence and energy levels
- Cambo fpso project
- Shell 3353
- Cross counter flow heat exchanger
- Bohr diagram for calcium ion
- What shell am i using
- Anti penultimate shell
- Shell hse management system
- Spancop
- Cs252 shell project
- Chris stolte shell
- Conjugate heat transfer ansys
- Adb shell cd
- Korku tettey
- Ssh secure shell client
- Lennot joensuu philadelphia
- Os shell
- Live shell pro
- Ordenamiento
- Stainless steel shell and tube heat exchanger
- Methane dot and cross diagram
- Shell sort knuth sequence
- Learner mindset shell
- Java expert system
- Two pass shell and tube heat exchanger
- Shell sort
- Fish that have fins and backbones
- Peela paragraph
- Java expert system shell
- North carolina state fruit
- Arbeitserlaubnisschein
- Merge insertion sort python
- Shell lube analyst
- Shell taşıt tanıma anahtarlık
- Volere requirements specification template
- Gene spadaro juvenile center