본문 바로가기
IT/리눅스

Bash Programming-2.Redirection

by 라떼야가자 2024. 7. 22.

https://www.gnu.org/software/bash/manual/html_node/Redirections.html

 

Redirections (Bash Reference Manual)

3.6 Redirections Before a command is executed, its input and output may be redirected using a special notation interpreted by the shell. Redirection allows commands’ file handles to be duplicated, opened, closed, made to refer to different files, and can

www.gnu.org

https://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html

 

BASH Programming - Introduction HOW-TO

 

tldp.org

 

 

배시에서 아주 많이 사용하는 리다이렉션(redirection)에 대해서 정리하려고 한다.

리다이렉션은 보통 어떤 출력결과를 파일 등 다른 곳으로 변경할 때 주로 사용된다.

연산자는 꺽쇠 "<", ">"이며 꺽쇠의 방향에 따라 어느 입력을 어느 출력으로 보내는지 결정된다.

(입력 > 출력 또는 출력 < 입력)

 

입출력 대상

  • 파일
  • /dev/fd/fd: 파일 디스크립터 fd (File Descriptor)
  • /dev/stdin: 파일 디스크립터 0, 표준 입력
  • /dev/stdout: 파일 디스크립터 1, 표준 출력
  • /dev/stderr: 파일 디스크립터 2, 표준 에러
  • /dev/tcp/host/port: TCP 소켓
  • /dev/udp/host/port: UDP 소켓

* 파일 디스크립터가 9보다 큰 것은 조심해서 사용해야 한다. 셸 내부적으로 사용되는 것과 충돌 가능성이 존재함.


리다이렉션(Redirection) 연산자(Operator) 종류

입력 리다이렉션

[n] word

 

출력 리다이렉션

[n]>[|]word

 

출력 리다이렉션을 추가

 

히어 문서(Here Documents)

 

히어 문자열(Here Strings)

 

 

 

예제

표준출력을 파일로 쓰기

ls -l > ls-l.txt

 

표준에러를 파일로 쓰기

grep da * 2> grep-erros.txt

 

표준출력을 표준에러로 보내기

grep da * 1>&2

 

표준에러를 표준출력으로 보내기

grep * 2>&1

 

표준에러와 표준출력을 파일로 쓰기

rm -r $(find / -name core) &> /dev/null

 

 

 

아직 작성중...