C.W.K.
Stream
Lesson 03 of 10 · published

Stderr Redirection — 2>, 2>&1, &>

~10 min · stderr, redirect, merge

Level 0창 구경꾼
0 XP0/95 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

파이프가 기본으론 안 옮기는 스트림

파이프는 stdout 만 옮겨. 에러는 그 뒤에 | 가 몇 개 있든 화면으로 가. 에러를 잡거나 숨기거나 파이프 태우려면 stderr 를 명시적으로 redirect.

평생 쓸 세 패턴

  • cmd 2> err.log — stderr 를 파일로.
  • cmd 2>/dev/null — stderr 묵음.
  • cmd 2>&1 — stderr 를 stdout 에 합침.

조합: cmd 2>&1 | grep ERROR 가 두 스트림 모두에서 에러 검색. cmd > out.log 2>&1 는 전부 한 파일로.

순서 중요

Redirection 은 왼쪽부터 처리, 각 &1 은 '지금 fd 1 이 가리키는 곳' 을 의미. 비교:

  • cmd > out.log 2>&1 → stdout 을 파일로, 그 다음 stderr 도 stdout 의 현재 목적지 (= 파일) 로. 둘 다 out.log.
  • cmd 2>&1 > out.log → stderr 가 stdout 의 현재 목적지 (= 화면) 로 가고 그 후에 stdout 만 파일로. 에러는 화면에 남음!

Bash 4+ 단축 &>

cmd &> out.log 가 둘 다. cmd &>> out.log 은 append. 분리 필요 없으면 > out.log 2>&1 보다 깔끔. POSIX sh 엔 없어 — 휴대성 있는 스크립트엔 long form.

Code

흔한 stderr 처리·bash
# Find without permission spam
find / -name 'todo.md' 2>/dev/null
# Capture everything in one log
./long_build.sh > build.log 2>&1
# See errors only on screen, save stdout to file
./long_build.sh > build.log
# Send only errors to a file
./long_build.sh 2> errors.log

External links

Exercise

순서 함정: ls /etc /no/such > out.log 2>&1 후 out.log 읽기. 이어서 ls /etc /no/such 2>&1 > out.log — 에러는 화면, stdout 만 파일. 다른 결과! 차이 외우기.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.