Linux Shell 명령어 정리

2019. 12. 8. 11:45coding

Path - Bash 환경설정


  • $PATH=$PATH:. → .추가 (.은 현재 작업 디렉토리) 하면 ./myprog 대신 myprog 로 실행 가능
  • 자신의 홈디렉토리의 .bahs_profile을 수정
    • 'PATH=$PATH:$HOME/bin' 부분에서 : 으로 구분하여 덧붙이면 된다.

CTRL 조합 명령


  • Ctrl + c : 프로세스의 종료
  • Ctrl + d : 입력의 끝
  • Ctrl + g : Bell (삑 소리)
  • Ctrl + h : 백스페이스 (backspace)
  • Ctrl + u : 입력줄을 지움
  • Ctrl + z : 포그라운드 작업을 잠시 멈충

Startup files


  • Script starting with .(dot) - ends with rc ("run command" —optional)
  • look for scripts before (or after) execution
  • usually they are for environment variable
  • each command knows its own startup file names (try ls -a)
  • bash (.bash_profile / .bashrc / .bash_logout ) : initialization for login shell for per-interactive shell, login shell clean-up file
  • sh (.profile)
  • vi (.exrc) : editor options
  • mail (.mailrc) : mail options
  • startx (.xinitrc) : x11 environment

Redirection


  • Output redirection (>) : 프로세스의 출력을 새로운 파일을 생성해서 기록
  • Output redirection (>>) : 프로세스의 출력을 지정한 파일의 마지막 부분에 추가
  • Input redirecion (<) : 프로세스의 입력으로 파일을 사용

Process / task / job


  • process : A process is an active entity, which requires a set of resources
  • task : A task represents the execution of a single process or multiple processes on a compute node
  • job : A collection of tasks that is used to perform a computation is known as job (batch jobs..)

Multitasking


  • Foreground : current task (Command Running at the $ prompt)
  • Background : Command running behind the scenes (not interactive → e.g text editor..)
    • An & sign at end of a simple command, pipeline, sequence of pipelines, a group of commands
    • Starts a sub-shell (commands are executed as a background process, does not take control of the keyboard)
    • A process id is displayed when it begins
    • Redirect the output to a file (if desired) → prevents background output on terminal
    • Background process cannot read from standard input, if they attempt to read from standard input, they terminate
  • Every command is assigned a unique number (Process id - pid)
  • **ps :** display currently running tasks
    • -a : all user processes
    • -u : user info
    • -x : not attached to a terminal
    • -e : ps to include all running processes
    • -f : ps to generate a full listing
    • -l : long listing
    • Column Meaning
      • S : the process state
      • UID : the effective user id of the process
      • PID : the process id
      • PPID : the parent process id
      • C : the percentage of CPU time that the process used in the last minute
      • PRI : the priority of the process
      • SZ : the size of the process's data and stack in kb
      • STIME : the time the process was created
      • TTY : the controlling terminal
      • TIME : the amount of CPU
      • CMD : The name of the command

Kill Command


  • kill [-9] Pid1 Pid2...
    • Stop (kill) a currently running process → 프로세스를 강제 종료하는 경우 사용
    • can only stop proceases
    • -9 : sure kill (signal 번호로 9번 - 강제종료 를 가장 많이 사용함)
    • kill -9 <PID of mytest> → mytest를 강제 종료

Job control


  • Foreground job
    • 명령어 라인을 실행시키거나 작업을 실행시키면 작업이 종료될 때까지 블록 상태가 되어 더이상 명령을 수행할 수 없는 상태
    • fg 명령어로 Background job을 Foreground job으로 바꿀 수 있음
  • Background job
    • 새로운 프로세스를 할당받아 작업을 실행시키고 사용자는 터미널에서 계속 다른 작업을 할 수 있는 상태
    • bg 명령어로 Foreground job 혹은 Suspended job을 Background job으로 바꿀 수 있음
  • jobs : List background jobs
  • kill %(n) : Kill background job n
  • wait : allows the shell to wait for one of its child processes to
  • **sleep (n)** : suspend execution for an interval (지정된 시간 n초 동안 실행을 일시 중지, 주로 쉘 스크립트에서 많이 사용)
  • **alias <명령어>="<별명>"** : 명령어에 다른 이름을 부여 (별명)
    • unalias <명령어> 명령으로 이미 설정되어 있는 별명을 해제
    • 별명을 작성할 때 명령어에 공백이 포함되면 "" 안에 기술해야 함
    • 로그아웃 시 정의가 무효되기 때문에 보통 로그인 설정 파일에 설정하는 경우가 많음
    • alias rm="rm -i" → rm을 rm -i 의 별명으로 지정

Shell Command


find [patname] [criteria]

  • Where actions
    • To include the pathname of the file that's just been found in command, use the special symbol {}
    • command must end with a ;
    • -exec : Executes command
    • -ok : the interactive version of —exec
  • $ find startingDir searchOptions commandToPerform
    • $ find . -name '*.c' -print
    • $ find .-mtime -14 -ls
    • $ find .-name'*.txt'-print
    • $ find / -size 0 -exec rm -i {} \;
    • $ find / -name'*.swp' -ok mv {} /tmp ';'

Filter Commands

  • Filter manipulates the input, and then sends the results to the standard output stream
  • Common filter commands
    • more, cat, cmp, cut, diff, head, tail, paste, sort, tr, uniq, wc, grep, sed, awk,...
  • Cat [options] [input files]
    • Concatenating files
    • -e : print $ at end of line
    • -n : number lines
    • -s : silent (no error messages)
    • -t : print tabs and form feeds
    • -u : unbuffered output
    • -v : print control characters
    • cat file1 file2 → using cat to combine
    • cat file1 → Displaying a file with cat
    • cat > file1 → creating a file with cat (> : input from keyboard)
  • head [options] [input files]
    • -N : number of lines
  • tail [options] [input file]
    • +N : Skip N-1 lines
    • -N : N lines from end
    • -l : measured by lines (default)
    • -c : meaured by characters
    • -b : measured by blocks
    • -r : output in reverse order
  • cut [options] [file list]
    • -c : character
    • -f : field
    • -d : delimeter
    • -s : suppress
  • sort [options] [field specifiers] [input files]
    • -c : check sequence
    • -t : alternatie delimeter
    • -n : numeric sort
    • -m : merge (not sort)
    • -u : unique keys
    • -f : fold
    • -r : reverse
    • -b : ignore leading blanks
    • -d : dictionary sort
    • sort by fields : fields within a line
      • when the data that control the data sequence are not at the beginning of the line, we need a field sort
      • the UNIX sort defines a field as a set of characters delimeted by a single blank of a tab
    • $ sort -k 3 data.txt
    • $ sort -k 2,3 data.txt
    • $ sort -k 3.3 data.txt
  • uniq [options] [input file]
    • -u : only nonrepeated lines output
    • -d : only repeated lines output
    • -c : add count to lines
    • -f : field
    • -s : character
  • wc [options] [input files]
    • -c : character count
    • -l : line count
    • -w : word count
  • cmp [options] file1 file2
    • -l : list
    • -s : suppress list
  • diff [options] files or directories
    • -b : ignore trailing blanks
    • -w : ignore whitespace
    • -i : ignore case
    • < 는 원래 파일, > 는 바뀐 파일
    • 5c5,8 → 원래 파일에서 5 line이 바뀐 파일에서 5~8번째 line 으로 내용이 변경되었다는 의미
  • Pipeline |
    • $ ps -ef | more
    • $ ps -ef | sort -k 2
    • $ ps -ef | sort -k 2 | head -5