😒 저 저 저 개념없는 나/🍎 Linux

[리눅스 | Linux] 리다이렉션 파이프라인

우주수첩 2024. 11. 25. 17:34
728x90

# 리눅스 표준 스트림 동작 과정

일반적으로 커맨드command로 실행되는 프로세스process
표준 입력 스트림
standard input stream ; stdin,
표준 출력 스트림
standard output stream; stdout과 오류 출력 스트림standard error stream ; stderr을 가지고 있다.

기본적으로 이 모든 스트림은 일반적인 문자열plain text로 콘솔console에 출력 하게 되어 있다.

 

 

 

# 리다이렉션

  • 표준 스트림의 흐름을 바꿔준다. 
    == 실행된 프로세스의 스트림을 콘솔이 아닌 파일로 사용하고 싶을 경우 사용.
기호 방향 의미
> 표준 출력 명령의 결과를 파일로 저장; 기존 파일 덮어씀
>> 표준 출력(append) 명령의 결과를 기존 파일에 추가
< 표준 입력 파일의 데이터를 명령에 입력

 

 

ex1 ) ls > ls.txt

root@civic-asp:/home# ls > ls.txt
root@civic-asp:/home# ls
WZNT  khj  ls.txt  ubuntu
root@civic-asp:/home# cat ls.txt 
WZNT
khj
ls.txt
ubuntu

 

  1. ls 명령어의 출력 결과를 ls.txt 파일에 저장
  2. ls의 출력 스트림을 ls.txt라는 파일로 사용 
  3. ls 명령어의 결과는 콘솔이 아닌 ls.txt파일에 기록

 

 

ex) head -n 2 < ls.txt

root@civic-asp:/home# head -n 2 < ls.txt
WZNT
khj

 

  1. ls.txt 에 처음 두 줄을 가져온다.
  2. ls.txt를 head의 입력 스트림으로 보낸다. 

 

 

ex) head -n 2 <ls.txt > ls2.txt

root@civic-asp:/home# head -n 2 < ls.txt > ls2.txt
root@civic-asp:/home# ls
WZNT  khj  ls.txt  ls2.txt  ubuntu
root@civic-asp:/home# cat ls2.txt 
WZNT
khj

 

1. ls txt의 내용을 head 명령어의 입력 스트림으로 전송

2. head 명령어는 입력받은 ls.txt의 내용에서 처음 2줄 출력

3. head 명령어의 출력스트림을 ls2.txt파일에 연결

4. head 명령어의 출력스트림은 콘솔이 아닌 ls2.txt에 연결되어있으므로 출력 결과를 ls2.txt에 저장. 

 

 

 

# 파이프라인

 

  • 프로세스간에 사용되는 리다이렉션
  • 기호 : |
    A|B -> 커맨드 A의 표준 출력을 커맨드 B의 표준 입력으로 사용. 
  • 프로세스의 출력 스트림을 다른 프로세스의 입력 스트림으로 사용할 때 리다이렉션 기호 사용시 오류 발생.
    일치하는 파일이 없거나 디렉토리가 없다고 오류메세지 발생

 

ex) ls | grep ls.txt

  • ls명령어의 출력스트림을 grep커맨드의 입력 스트림으로 보내고 grep커맨드의 인자 값으로 ls.txt를 준 것.
  • 현재 디렉토리에 ls.txt 파일이 있을 경우 결과를 콘솔에 출력.

 

 

 

# 파이프 라인 + 리다이렉션

 

ex) ls | grep ls.txt > ls3.txt

root@civic-asp:/home# ls | grep ls.txt > ls3.txt
root@civic-asp:/home# ls
WZNT  khj  ls.txt  ls2.txt  ls3.txt  ubuntu
root@civic-asp:/home# cat ls3.txt
ls.txt

1. ls명령어의 출력 스트림을 grep의 입력 스트림으로 연결

2.ls 명령어의 출력물을 grep명령어로 필터링 한 뒤 나온 결과값을 ls3.txt 파일에 기록

 

 

ex)$ head dummy.txt 2>> error.txt

root@civic-asp:/home# head dummy.txt 2>> error.txt
root@civic-asp:/home# ls
WZNT  error.txt  khj  ls.txt  ls2.txt  ls3.txt  ubuntu
root@civic-asp:/home# cat error.txt
head: cannot open 'dummy.txt' for reading: No such file or directory
root@civic-asp:/home#
  1. dummy.txt의 파일의 처음 10줄을 읽어 출력하고 오류 스트림은 error.txt에 연결하여 기록
  2. dummy.txt 파일이 없을 경우 오류 메세지가 error.txt파일에 기록

 

 

예제

2024.11.26 - [😒 저 저 저 개념없는 나/🍎 Linux] - [리눅스 | Linux] 파이프라인, 리다이렉션 적용 예제

 

 

 

참고 url:

https://jdm.kr/blog/74

 

 

728x90