74
LINUX COMMAND 장장장

Linux command for beginners

  • Upload
    -

  • View
    269

  • Download
    15

Embed Size (px)

Citation preview

Page 1: Linux command for beginners

LINUX COMMAND 장수경

Page 2: Linux command for beginners

Part 1 – Learning The Shell

Page 3: Linux command for beginners

Why use the command-line?

"Under Linux there are GUIs (graphical user interfaces), where you can point and click and drag, and hopefully get work done without first reading lots of documentation. The traditional Unix environment is a CLI (command line interface), where you type com-mands to tell the computer what to do. That is faster and more powerful, but requires finding out what the commands are."

https://help.ubuntu.com/community/UsingTheTerminal?action=show&redirect=BasicCommands

Page 4: Linux command for beginners

Start Terminal

Applications menu -> Accessories -> Terminal.

Keyboard Shortcut: Ctrl + Alt + T

Terminal EmulatorsWhen using a graphical user interface, we need another program called a terminal emulatorto interact with the shell. If we look through our desktop menus, we will probably findone. KDE uses konsole and GNOME uses gnome-terminal, though it's likelycalled simply “terminal” on our menu. There are a number of other terminal emulatorsavailable for Linux, but they all basically do the same thing; give us access to the shell.You will probably develop a preference for one or another based on the number of bellsand whistles it has.

Page 5: Linux command for beginners

Shell Prompt

SHELL : 키보드로 입력한 명령어를 운영체계에 전달하여 이 명령어를 실행하게 하는 프로그램 # : root 로 접속했을 경우 / sudo 로 루트권한을 얻었을 경우 $ : 다른 유저로 접속했을 경우

username @ manchinename : working directory $

Page 6: Linux command for beginners

How Many Different Types of Shell Are There?

echo $SHELL 현재 사용중인 쉘 프로그램의 경로 출력 Linux 에서는 대부분 bash 사용 chsh (change shell) 패스워드 입력 후 쉘 변경 가능

Debian Almquist shell (dash)

bourne again shell (bash)

korn (KSH)

csh/tsch

zsh

http://linux.about.com/cs/linux101/g/shell_command.htm

-echo $SHELL 현재 사용중인 쉘 프로그램의 경로 출력 Linux 에서는 대부분 bash 사용 -chsh (change shell) 패스워드 입력 후 쉘 변경 가능

Page 7: Linux command for beginners

Ubuntu Directory

이와 같은 shell 명령어들은 일종의 실행파일 , 프로그램이다 . 단순한 명령어들은 built-in command 라고 하여 bash shell 에 아예 내장되어 있는 경우도 있고 ,

그렇지 않은 경우 파일시스템 ( 루트 디렉토리 ) 의 /bin 디렉토리 혹은 /usr/bin 디렉토리에 모여있다 . bin 의 어원은 binary file. 컴퓨터가 바로 실행할 수 있는 기계어 실행프로그램들이다 . bin 디렉토리에 들어가서 실행파일들 이름을 찬찬히 살펴보자 . 리눅스 눈칫밥 3 개월만 돼도 친숙한 이름들이 많이 보일 것이다 .

일단 /bin 에는 좀 더 원초적이고 단순하며 저급한 명령어들이 모여있다 . 컴퓨터 구동에 필요한 최소한만 있다고 한다 . 가령 rm (remove), mkdir(make dir) 등등 정녕 이게 프로그램인가 싶은 기본적인 것들만 있다 .반면 /usr/bin 에는 좀 고등한 것들이 많이 존재하는데 ,  가령 g++ 이나 apt-get, w3m, nautilus 과 같은 것들이 있다 . 

즉 , 일반적으로 /bin 에는 운영체제 기본 프로그램들이 모여있고 /usr/bin 에는 추가 프로그램들이 모여있다 .

http://egloos.zum.com/ttti07/v/3512271

Page 8: Linux command for beginners

Command

[command] [argument1] [argument2]…

Command 에 따라 사용가능한 argument 의 형식 등이 다르다 • command 의 동작 방법을 명시하는 option• 파일이나 디렉토리의 이름 / 경로 • 임의의 문자열 • Etc…

- : 단축 옵션-- : long 옵션여러 옵션을 한 명령어에 연이어 사용할 수 있다$ls -a -l wheel ls 는 command 이고 -a, -l, wheel 은 arguments $ls -lt --reverse

Page 9: Linux command for beginners

man commandThe man command is used to show you the manual of other commands. Try "man man" to get the man page for man itself.

Searching for man filesIf you aren't sure which command or application you need to use, you can try searching the man files.

•man -f foo( 함수이름 ) searches only the titles of your system's man files. Try "man -f gnome", for example. Note that this is the same as doing whatis command. •man -k foo will search the man files for foo. Try "man -k nautilus" to see how this works. Note that this is the same as doing apropos command.

Page 10: Linux command for beginners

Manipulating Files And Directories

1. ls, cd, pwd command

2. mkdir, rm command

3. cp command

4. wildcards

5. mv command

6. ln, touch command

Page 11: Linux command for beginners

1. ls, cd, pwd command

ls – directory listingls -al – formatted listing with hidden filescd dir - change directory to dircd – change to home

Examples:

cd /home/user/docs/Letter.txt 절대주소 cd docs/Letter.txt 상대주소 cd / root 로 이동 cd . 현재 디렉토리 유지 cd .. 상위 디렉토리로 이동 cd ~ or cd 홈 디렉토리로 이동 cd ~noname noname 의 홈 디렉토리로 이동 cd - 이전 디렉토리로 이동

pwd – printing working directory

Page 12: Linux command for beginners

2. mkdir, rm command

mkdir dir – create a directory dir $ mkdir dir1 dir2

rm file – delete filerm -r dir – delete directory dirrm -f file – force remove filerm -rf dir – force remove directory dir

Page 13: Linux command for beginners

3. cp command

cp file1 file2 – copy file1 to file2. file2 가 이미 있다면 file1 내용을 그대로 덮어쓰게 된다 . file2 가 없으면 새로 생성된다 .cp -r dir1 dir2 – (--recursive) copy dir1 to dir2; create dir2 if it doesn't exist 디렉토리와 그 안의 내용까지 복사한다 .

$ cp *.html destination

$ cp /etc/passwd .

Page 14: Linux command for beginners

4. wildcards

Page 15: Linux command for beginners

5. mv command

mv file1 file2 – rename or move file1 to file2if file2 is an existing directory, moves file1 into directory file2

$ mv passwd fun

$ mv fun dir1

$ mv dir1/fun dir2 (dir1 에 있는 fun 파일을 dir2 로 이동 )

$ mv dir2/fun .

Page 16: Linux command for beginners

6. ln, touch command

ln -s file link – create symbolic link link to file $ ln –s fun fun-sym$ ln –s ../fun dir1/fun-sym

touch file – create or update file

symbolic link

심볼릭 링크는 참조될 파일이나 디렉토리를 가리키는 텍스트 포인터가 포함된 특수한 파일을 생성한다 . 이러한 점에서 윈도우의 바로가기와 매우 흡사한 방식이다 . 심볼릭 링크가 참조하고 있는 파일과 심볼릭 링크 그 자체는 서로 구분하기 힘들 정도다 . 예를 들면 , 심볼릭 링크에 편집을 하게 되면 심볼릭 링크가 참조하고 있는 파일도 역시 똑같은 변경이 이루어진다 . 하지만 심볼릭 링크를 삭제하는 경우엔 그 링크만 삭제되고 파일은 남아있다 . 심볼릭 링크를 삭제하기 전에 파일을 지웠다면 심볼릭 링크는 살아있지만 이 링크는 아무것도 가리키지 않게 된다 . 이러한 경우를 링크가 깨졌다고 표현한다 . 많은 쉘에서 ls 명령어로 인해 빨간색이나 다른 색상으로 깨진 링크를 볼 수 있다 .

Page 17: Linux command for beginners

Redirection

1. Redirecting Standard Input, Output, And Error- cat command

2. pipelines

3. Filters - uniq, wc, grep, cut, paste, join, head, tail, tee command

In this lesson we are going to unleash what may be the coolest feature of the commandline. It's called I/O redirection ( 입출력 방향지정 ). The “I/O” stands for input/output and with this facility you can redirect( 재지정 ) the input and output of commands to and from files, as well as connect multiple commands to-gether into powerful command pipelines.

Page 18: Linux command for beginners

1. Standard Input, Output, And Error

programs such as ls actually send their results to a special file called standard output (often expressed as stdout) and their status messages to another file called standard error (stderr). By default, both standard output and standard error are linked to the screen and not saved into a disk file.In addition, many programs take input from a facility called standard input (stdin) whichis, by default, attached to the keyboard.

Page 19: Linux command for beginners

Redirecting Standard Output

I/O redirection allows us to redefine where standard output goes. To redirect standardoutput to another file instead of the screen, we use the “>” redirection operator fol-lowed by the name of the file.

$ ls -l /usr/bin > ls-output.txt$ ls -l ls-output.txt$ less ls-output.txt

$ ls -l /bin/usr > ls-output.txt 오류메세지만을 만들기 때문에 크기가 0 인 파일로 덮어씀$ > ls-output.txt 위 원리를 이용하여 새로운 빈 파일을 만들거나 파일을 잘라냄$ ls -l /usr/bin >> ls-output.txt 출력할 내용을 파일에 이어서 작성 , 존재하지 않는 파일이면 파일 생성

Page 20: Linux command for beginners

Redirecting Standard Error

Redirecting standard error lacks the ease of a dedicated redirection operator. To redirectstandard error we must refer to its file descriptor. A program can produce output on anyof several numbered file streams. While we have referred to the first three of these filestreams as standard input, output and error, the shell references them internally as file descriptors 0, 1 and 2, respectively. The shell provides a notation for redirecting files us-ing the file descriptor number. Since standard error is the same as file descriptor number 2, we can redirect standard error with this notation:

$ ls -l /bin/usr 2> ls-error.txt

The file descriptor “2” is placed immediately before the redirection operator to performthe redirection of standard error to the file ls-error.txt.

Page 21: Linux command for beginners

Redirecting Standard Output And Standard Error To One File

$ ls -l /bin/usr > ls-output.txt 2>&1

Using this method, we perform two redirections. First we redirect standard output to thefile ls-output.txt and then we redirect file descriptor 2 (standard error) to file descrip-tor one (standard output) using the notation 2>&1.

or

$ ls -l /bin/usr &> ls-output.txt

Disposing Of Unwanted OutputThis “/dev/null” file isa system device called a bit bucket which accepts input and does nothing with it.$ ls -l /bin/usr 2> /dev/null

Page 22: Linux command for beginners

Redirecting Standard Input- cat command

cat [file...]- Concatenate files and print on the standard output 파일과 표준 출력을 연결하나이상의 파일을 읽어들여서 표준 출력으로 그 내용을 복사주로 짧은 텍스트 파일을 표시할 때 , 여러 파일을 하나로 합칠 때$ cat ls-output.txt

Say we have downloaded a large file that has been split into multiple parts (multimedia files are of-ten split this way on Usenet), and we want to join them back together. If the files were named:

movie.mpeg.001 movie.mpeg.002 ... movie.mpeg.099we could join them back together with this command:$ cat movie.mpeg.0* > movie.mpeg

$ cat > lazy_dog.txtThe quick brown fox jumped over the lazy dog.텍스트 입력 후 CTRL-D

Page 23: Linux command for beginners

2. PipelinesUsing the pipe operator “|” (vertical bar), the standard output of one command can be piped into the standard input of another: command1 | command2

$ ls -l /usr/bin | less

more, less – output the contents of file

Page 24: Linux command for beginners

3. Filters - uniq, grep, wc command

Pipelines are often used to perform complex operations on data. It is possible to put several commands to-gether into a pipeline. Frequently, the commands used this way are referred to as filters. Filters take input, change it somehow and then output it.

sort - Sort lines of text uniq - Report or omit repeated lines$ ls /bin /usr/bin | sort | uniq | less 중복된 내용 삭제$ ls /bin /usr/bin | sort | uniq -d | less 중복된 내용 표시 grep - Print lines matching a pattern (“-i” : 대소문자 구분안함 , “-v” : 패턴과 일치하지않는 것 출력 )$ ls /bin /usr/bin | sort | uniq | grep zip

wc (word count) - Print newline, word, and byte counts for each file$ wc ls-output.txt7902 64566 503634 ls-output.txt$ ls /bin /usr/bin | sort | uniq | wc –l 정렬된 목록에서 항목개수 ( -l :line 수만 )

Page 25: Linux command for beginners

3. Filters – cut, paste, join command

cut – Remove sections from each line of files

paste – Merge lines of files join – Join lines of two files on a common field( 참고 ) awk – 행 단위로 텍스트 파일을 편집

Page 26: Linux command for beginners

3. Filters - head, tail, tee command

head - Output the first part of a file 앞 10 줄 tail – Output the last part of a file 뒤 10 줄$ head -n 5 ls-output.txt 앞 5 줄 tail -f file – output the contents of file as it grows, starting with the last 10 lines$ tail -f /var/log/messages 실시간으로 로그 파일 확인 , CTRL-C 누를 때까지 계속 tee - Read from standard input and write to standard output and files 작업이 진행되고 있을 때 중간 지점의 파이프라인에 있는 내용을 알고 싶을 때 유용$ ls /usr/bin | tee ls.txt | grep zip

Page 27: Linux command for beginners

Expansion & Quoting

1. Expansion

2. Quoting

Page 28: Linux command for beginners

1. Expansion

Each time you type a command line and press the enter key, bash performs several pro-cesses upon the text before it carries out your command. We have seen a couple of cases of how a simple character sequence, for example “*”, can have a lot of meaning to the shell. The process that makes this happen is called expansion.

echo – Display a line of text

$ echo this is a testthis is a test

Pathname Expansion 경로명 확장 ( 와일드카드로 동작하는 방식 )

$ echo *Desktop Documents ls-output.txt Music Pictures Public Templates Videos

Page 29: Linux command for beginners

1. Expansion

Tilde(~) Expansion 틸드 확장$ echo ~ 홈 디렉토리/home/me

Arithmetic Expansion 산술 확장$ echo $((2 + 2))4

$ echo $(($((5**2)) * 3))75

Page 30: Linux command for beginners

1. Expansion

Brace Expansion 중괄호 확장$ echo Front-{A,B,C}-BackFront-A-Back Front-B-Back Front-C-Back$ echo {001..15}001 002 003 004 005 006 007 008 009 010 011 012 013 014 015

Parameter Expansion 매개변수 확장$ echo $USER 사용자명 표시$ printenv | less 사용가능한 변수목록 보기Command Substitution 명령어 치환which – show which app will be run by default 실행프로그램의 위치 표시$ ls -l $(which cp) or ls -l `which cp` 경로명 전체를 알지 못해도 cp 프로그램 내용볼수있다-rwxr-xr-x 1 root root 71516 2007-12-05 08:58 /bin/cp$ file $(ls -d /usr/bin/* | grep zip)

Page 31: Linux command for beginners

2. Quoting

Double Quotes쉘에서 사용하는 특수한 기호들이 가진 의미가 없어지고 대신 일반적인 문자들로 인식단 , $,\,’ 기호는 예외즉 단어분할 ( 공백삭제 ), 경로명 확장 , 틸드 확장 , 괄호 확장을 숨길 수 있지만 매개변수 확장 , 산술 확장 , 명령어 치환은 그대로 시행$ ls -l two words.txtls: cannot access two: No such file or directoryls: cannot access words.txt: No such file or directory$ ls -l "two words.txt"-rw-rw-r-- 1 me me 18 2008-02-20 13:03 two words.txt

Page 32: Linux command for beginners

2. Quoting

Single Quotes

$ echo text ~/*.txt {a,b} $(echo foo) $((2+2)) $USERtext /home/me/ls-output.txt a b foo 4 me$ echo "text ~/*.txt {a,b} $(echo foo) $((2+2)) $USER"text ~/*.txt {a,b} foo 4 me$ echo 'text ~/*.txt {a,b} $(echo foo) $((2+2)) $USER'text ~/*.txt {a,b} $(echo foo) $((2+2)) $USER

Escaping Characters (backslash)

$ mv bad\&filename good_filename

Page 33: Linux command for beginners

Advanced Keyboard Tricks

1. Command line editing

2. Completion

3. Using history

Page 34: Linux command for beginners

1. Command Line Editing

Page 35: Linux command for beginners

2. Completion

Completion 자동완성 : 탭키

Page 36: Linux command for beginners

3. Using History$ history | lessBy default, bash stores the last 500 commands you have entered.

$ history | grep /usr/bin88 ls -l /usr/bin > ls-output.txt

The number “88” is the line number of the command in the history list. We could use thisimmediately using another type of expansion called history expansion. $ !88

Page 37: Linux command for beginners

Permission

$ ls -l foo.txt-rw-rw-r-- 1 me me 0 2008-03-06 14:52 foo.txt

Page 38: Linux command for beginners

Permission

Page 39: Linux command for beginners

Permission

id – Display user identity

chmod – Change a file's mode 파일소유자나 슈퍼유저만이 가능(1) 8 진법$ chmod 600 foo.txt$ ls -l foo.txt-rw------- 1 me me 0 2008-03-06 14:52 foo.txtchmod 777 – read, write, execute for allchmod 755 – rwx for owner, rx for group and world

4 – read (r) 2 – write (w) 1 – execute (x)

Page 40: Linux command for beginners

Permission

(2) Symbolic Notation ( 참고 )

Page 41: Linux command for beginners

Permission

umask – Set the default file permissionssu – Run a shell as another usersudo – Execute a command as another userchown – Change a file's ownerpasswd - Changing a password

Page 42: Linux command for beginners

Permission

sudo command

How do you use sudo !!? Simply. Imagine you have entered the following command:$apt-get install rangerThe words "Permission denied" will appear unless you are logged in with elevated privileges. This elevates privileges to the root-user administrative level temporarily, which is necessary when working with directories or files not owned by your user account.sudo !! runs the previous command as sudo. So the previous command now becomes:$sudo apt-get install ranger

Logging in as another user (Please don't use this to become root)$sudo -i -u <username>

Enabling the root account$sudo -iTo enable the root account (i.e. set a password) use: $sudo passwd root

Enabling the root account is rarely necessary. Almost everything you need to do as administrator of an Ubuntu system can be done via sudo or gksudo. If you really need a persistent root login, the best alter-native is to simulate a root login shell using the following command...

Page 43: Linux command for beginners

Process

ps – display your currently active processes

TTY(teletype) : the controlling terminal for the process

Page 44: Linux command for beginners

Process

top ('table of processes') – display all running processes jobs – List active jobsbg – lists stopped or background jobs; resume a stopped job in the backgroundfg – brings the most recent job to foregroundfg n – brings job n to the foreground

kill – Send a signal to a process$ kill 28401 프로세스 종료[1]+ Terminated xlogo작업번호 1 인 xlogo 프로그램을 종료함killall – Kill processes by nameshutdown – Shutdown or reboot the system

Page 45: Linux command for beginners

Part 2 – Configuration And The Envi-ronment

Page 46: Linux command for beginners

The Environment

What Is Stored In The Environment?The shell stores two basic types of data in the environment, though, with bash, thetypes are largely indistinguishable. They are environment variables and shell variables.Shell variables are bits of data placed there by bash, and environment variables are basically everything else. In addition to variables, the shell variables also stores some programmatic data, namely aliases and shell functions.

Page 47: Linux command for beginners

The Environment

alias – Create an alias for a command$ aliasalias l.='ls -d .* --color=tty'alias ll='ls -l --color=tty'alias ls='ls --color=tty'alias vi='vim'alias which='alias | /usr/bin/which --tty-only --read-alias –showdot --show-tilde'

Page 48: Linux command for beginners

The EnvironmentHow Is The Environment Established?

What's A Startup File And What’s In That?When we log on to the system, the bash program starts, and reads a series of configuration scripts called startup files, which define the default en-vironment shared by all users.

If the file "~/.bashrc" exists, thenread the "~/.bashrc" file.

Page 49: Linux command for beginners

The Environment

Modifying The Environment$ cp .bashrc .bashrc.bak 만약을 위해 백업파일 만듬$ nano .bashrc nano 편집기로 다음 내용을 추가# Change umask to make directory sharing easierumask 0002# Ignore duplicates in command history and increase# history size to 1000 linesexport HISTCONTROL=ignoredupsexport HISTSIZE=1000# Add some helpful aliasesalias l.='ls -d .* --color=auto'alias ll='ls -l --color=auto‘

Ctrl-o : save, Ctrl-x : exit nano$ source .bashrc 변경사항 적용 =. .bashrc

Page 50: Linux command for beginners

VIM editor

Page 51: Linux command for beginners

VIM editor* 입력 명령어 i 현재 커서 위치에 삽입 ( 왼쪽 ) a 현재 커서 위치 다음에 삽입 o 현재 커서가 위치한 줄의 아랫줄에 삽입 O 현재 커서가 위치한 줄의 바로 위에 삽입 I 현재 커서가 위치한 줄의맨 앞에 삽입 A 현재 커서가 위치한 줄의 맨 뒤에 삽입* 지우기 명령어 x 현재 커서 위치의 문자를 삭제 dd 현재 커서가 위치한 줄을 삭제 dw 현재 커서가 위치한 단어를 삭제 d$ 현재 커서가 위치한 곳부터 그 행의 끝까지 삭제 dG 현재 커서가 위치한 행부터 편집문서의 마지막 줄까지 삭제*. 삭제한 내용은 바로 지워지지 않고 버퍼에 저장되므로 붙여넣기 하거나 취소 할 수 있다 .

* 복사하기와 붙이기 yy(=Y) 현재 커서가 위치한 줄을 버퍼에 복사 (nyy => 현재 커서가 위치한 곳부터 아래로 n 라인을 버퍼에 복사한다 ) yw 현재 커서가 위치한 단어를 버퍼에 복사 (nyw => 현재 커서가 위치한 단어부터 오른쪽으로 n 개의 단어를 버퍼에 복사한다 ) p 버퍼에 들어 있는 내용을 현재 커서가 위치한 줄의 아래에 붙이기 P 버퍼에 들어 있는 내용을 현재 커서가 위치한 줄의 위에 붙이기* 치환 r 현재 위치의 문자를 한개만 바꾼다 . R 현재 커서위치에서 오른쪽으로 esc 키를 입력할 때 까지 바꾼다 . cw 현재 위치의 단어를 바꾼다 . cc 현재 커서가 위치한 줄을 바꾼다 . C 현재 커서가 위치한 곳으로부터 줄의 끝까지 바꾼다 . ~ 대소문자를 서로 바꾼다 .* 취소 명령어 u 방금 한 명령을 취소한다 . U 현재 커서가 위치한 줄에 대한 편집 명령을 취소한다 . ^R (=redo) 취소한 명령을 다시 취소 (vim) . 방금한 명령을 되풀이 한다 .

Page 52: Linux command for beginners

VIM editor

* 이동 명령어 정리 ^b(back) 한 화면 위로 이동 ^u(up) 반 화면 위로 이동 ^f(forward) 한 화면 아래로 이동 ^d(down) 반 화면 아래로 이동 e 한 단어 뒤로 이동 b 한 단어 앞으로 이동 0 줄의 제일 처음부터 이동 $ 줄의 제일 끝으로 이동

Page 53: Linux command for beginners

VIM editor

스크립트 작성을 용이하게 해주는 옵션:syntax on 구문 강조 기능 . 쉘 구문마다 다른 색상으로 표시해주기 때문에 프로그래밍 오류를 쉽게 찾아낼 수 있다 . vim editor 의 풀버전이 설치되어 있어야 한다 .

:set hlsearch 검색 결과를 강조하여 표시 .

:set autoindent 자동 들여쓰기 기능 . 사용하지 않으려면 CTRL-D

이 옵션들을 영구적으로 적용하려면 ~/.vimrc 파일에 이 옵션을 추가 ( 콜론기호는 제외하고 입력 )

Page 54: Linux command for beginners

Part 3 – Common Tasks And EssentialTools

Page 55: Linux command for beginners

Networking

Networkping host – ping host and output results 네트워크 호스트로 고유 패킷 (IMCP ECHO-REQUEST) 전송whois domain – get whois information for domaindig domain – get DNS information for domaindig -x host – reverse lookup hostwget file – download file$wget http://sourceforge.net/projects/antix-linux/files/Final/MX-krete/antiX-15-V_386-full.iso/downloadwget -c file – continue a stopped download

SSH(Secure Shell)ssh user@host – connect to host as user 원격호스트와 안전하게 통신ssh -p port user@host – connect to host on port as userssh-copy-id user@host – add your key to host for user to enable a keyed or password-less login

Page 56: Linux command for beginners

Searching

locate – Find files by name 파일명으로 파일 찾기$ locate bin/zip zip 으로 시작하는 프로그램 ( 명령어 ) 찾기$ locate zip | grep bin zip 문자열이 포함된 프로그램 찾기find – Search for files in a directory hierarchy주어진 디렉토리 트리내에서 특정조건에 부합하는 파일 검색하기$ find ~ -type d | wc –l -type d: 검색결과에서 디렉토리 목록만 보기

Page 57: Linux command for beginners

Searching

$ find ~ \( -type f -not -perm 0600 \) -or \( -type d -not -perm 0700 \)파일들의 퍼미션이 0600 으로 설정되어 있지 않거나 디렉토리의 퍼미션이 0700 으로 설정되어 있지 않은지 확인$ find ~ -type f -name '*.BAK' –delete 백업파일 확장자를 가진 파일을 삭제

Page 58: Linux command for beginners

Archiving And Backup

Compressing Files 파일 압축하기gzip file – compresses file and renames it to file.gzgzip -d file.gz – decompresses file.gz back to filebzip2 file – 속도는 느리지만 고성능 압축zip –r file.zip file – zip 파일로 압축 . 윈도우 시스템과 파일을 교환할때 (-r: 하위디렉토리 포함 )

Archiving Files 파일 보관하기 (많은 파일들을 모아서 하나의 큰 파일로 묶는 과정 )tar cf file.tar files – create a tar(tape archive) named file.tar containing filestar xf file.tar – extract the files from file.tar 아카이브 해제tar czf file.tar.gz files – create a tar with Gzip compressiontar xzf file.tar.gz – extract a tar using Gziptar cjf file.tar.bz2 – create a tar with Bzip2 compressiontar xjf file.tar.bz2 – extract a tar using Bzip2f : 아카이브의 이름을 지정

Page 59: Linux command for beginners

Regular Expressions

Simply put, regular expressions are symbolic notations used to identify patterns in text. In some ways, they resemble the shell’s wildcard method of matching file and path-names, but on a much grander scale.

http://coffeenix.net/doc/regexp/node17.html

[^bg] 괄호표현식 안의 ^ 는 부정의 의미 , ^[A-Z] 괄호표현식안의 –는 문자범위

Page 60: Linux command for beginners

Regular Expressions

http://regexr.com/정규 표현식에 대한 도움말과 각종 사례들을 보여주는 서비스로 정규표현식을 라이브로 만들 수 있는 기능도 제공하고 있다 .

Page 61: Linux command for beginners

Regular Expressions

https://www.blackbagtech.com/blog/2013/05/08/digital-forensics-regular-expressions-regex-%E2%80%93-part-two/

Page 62: Linux command for beginners

Regular Expressions

Page 63: Linux command for beginners

Compiling Programs

Simply put, compiling is the process of translating source code (the human-readable description of a pro-gram written by a programmer) into the native language of the computer’s processor.The computer’s processor (or CPU) works at a very elemental level, executing programsin what is called machine language. This is a numeric code that describes very small operations, such as “add this byte,” “point to this location in memory,” or “copy this byte.” Each of these instructions is expressed in binary (ones and zeros). This problem was overcome by the advent of assembly language, which replaced the numeric codes with (s-lightly) easier to use character mnemonics such as CPY (for copy) and MOV (for move). Programs written in assembly language are processed into machine language by a program called an assembler. Assembly lan-guage is still used today forcertain specialized programming tasks, such as device drivers and embedded systems.

Page 64: Linux command for beginners

Compiling ProgramsWe next come to what are called high-level programming languages. They are called this because they allow the programmer to be less concerned with the details of what the processor is doing and more with solving the problem at hand. While there are many popular programming languages, two predominate. Most programswritten for modern systems are written in either C or C++. In the examples to follow, we will be compiling a C pro-gram.Programs written in high-level programming languages are converted into machine languageby processing them with another program, called a compiler. Some compilers translate high-level instructions into assembly language and then use an assembler to perform the final stage of translation into machine language.

A process often used in conjunction with compiling is called linking. There are many common tasks performed by programs. Take, for instance, opening a file. Many programs perform this task, but it would be wasteful to have each program implement its own routine to open files. It makes more sense to have a single piece of programming that knowshow to open files and to allow all programs that need it to share it. Providing support for common tasks is accom-plished by what are called libraries. They contain multiple routines, each performing some common task that multi-ple programs can share. If we look in the /lib and /usr/lib directories, we can see where many of them live. A pro-gram called a linker is used to form the connections between the output of the compiler and the libraries that the compiled program requires. The final result of this process is the executable program file, ready for use.

Page 65: Linux command for beginners

Compiling Programs

There are programs such as shell scripts that do not require compiling.They are executed directly. These are written in what are known as scripting or interpreted languages. These languages have grown in popularity in recent years and include Perl, Python, PHP, Ruby, and many others.

Scripted languages are executed by a special program called an interpreter. An interpreter inputs the pro-gram file and reads and executes each instruction contained within it. In general, interpreted programs exe-cute much more slowly than compiled programs. This is because that each source code instruction in an in-terpreted program is translated every time it is carried out, whereas with a compiled program, a source code instruction is only translated once, and this translation is permanently recorded in the final exe-cutable file.

Page 66: Linux command for beginners

Compiling Programs

Install from source:./configuremakemake install

make – Utility to maintain programs

Page 67: Linux command for beginners

Part 4 – Writing Shell Scripts

Page 68: Linux command for beginners

Writing Shell Script

In the simplest terms, a shell script is a file containing a series of commands. The shellreads this file and carries out the commands as though they have been entered directly on the command line.The shell is somewhat unique, in that it is both a powerful command line interface to thesystem and a scripting language interpreter.

Page 69: Linux command for beginners

Writing Shell Script

How To Write A Shell Script

To successfully create and run a shell script, we need to do three things:1. Write a script. Shell scripts are ordinary text files. So we need a text editor towrite them. The best text editors will provide syntax highlighting, allowing us tosee a color-coded view of the elements of the script. Syntax highlighting will helpus spot certain kinds of common errors. vim, gedit, kate, and many other editorsare good candidates for writing scripts.2. Make the script executable. The system is rather fussy about not letting any oldtext file be treated as a program, and for good reason! We need to set the scriptfile’s permissions to allow execution.3. Put the script somewhere the shell can find it. The shell automatically searchescertain directories for executable files when no explicit pathname is specified. Formaximum convenience, we will place our scripts in these directories.

Page 70: Linux command for beginners

Writing Shell Script1. Write a script.

#!/bin/bash# This is our first script.echo 'Hello World!'

2. Make the script executable.$ ls -l hello_world-rw-r--r-- 1 me me 63 2009-03-07 10:10 hello_world$ chmod 755 hello_world$ ls -l hello_world-rwxr-xr-x 1 me me 63 2009-03-07 10:10 hello_world

3. Put the script somewhere the shell can find it.In order for the script to run, we must precede the script name with an explicit path.

$ ./hello_world$ mkdir bin ~/bin 디렉토리는 개인적인 용도로 사용하려는 스크립트를 저장하기에 적합한 장소$ mv hello_world bin$ hello_worldHello World!

#!(shebang)뒤따라오는 스크립트를 실행하기 위한 인터프리터의 이름을 시스템에 알려준다 .모든 쉘 스크립트 첫줄에 반드시 존재해야 한다 .

Page 71: Linux command for beginners

Part 5 – etc..

Page 72: Linux command for beginners

Shortcuts

Ctrl+C – halts the current commandCtrl+Z – stops the current command, resume withfg in the foreground or bg in the backgroundCtrl+D – log out of current session, similar to exitCtrl+W – erases one word in the current lineCtrl+U – erases the whole lineCtrl+R – type to bring up a recent command!! - repeats the last commandexit – log out of current session

Ctrl+K - Cuts text from the cursor until the end of the lineCtrl+Y - Pastes textCtrl+E or End - Move cursor to end of lineCtrl+A or Home - Move cursor to the beginning of the lineALT+F - Jump forward to next spaceALT+B - Skip back to previous spaceALT+Backspace - Delete previous wordCtrl+W - Cut word behind cursorShift+Insert - Pastes text into terminal

Page 73: Linux command for beginners

Happy New Year !Get Your Fortune Told Another one that isn't particularly useful but just a bit of fun is the fortune command.Like the sl command you might need to install it from your repository first.sudo apt-get install fortune-modThen simply type the following to get your fortune toldfortune 

Get A Cow To Tell Your Fortune Finally get a cow to tell you your fortune using cowsay.Type the following into your terminal:fortune | cowsay If you have a graphical desktop you can use xcowsay to get a cartoon cow to show your fortune:fortune | xcowsaycowsay and xcowsay can be used to display any message. For example to display "Hello World" simply use the following command:cowsay "hello world"

http://linux.about.com/od/commands/tp/11-Linux-Terminal-Commands-That-Will-Rock-Your-World.01.htmhttps://www.digitalocean.com/community/tutorials/top-10-linux-easter-eggs

Page 74: Linux command for beginners

Referencehttp://linuxcommand.org/tlcl.php

http://files.fosswire.com/2007/08/fwunixref.pdf