Linux에서 콘솔 내용을 파일로 저장하기

원문 : http://linux.byexamples.com/archives/349/how-to-redirect-output-to-a-file-as-well-as-display-it-out/

standard output을 파일로 redirect시키는 방법은 간단하다. 그냥 redirection 기호만 사용하면 된다. 아래는 예제다

echo “hello world” > test.txt

하지만 이렇게 하면 콘솔에는 아무것도 보이지 않는다. 콘솔에도 보이고 파일에도 저장되게 하려면? 정답은 tee 명령이다

echo “hello world” | tee test.txt

파일 뒤에 계속 내용을 이어서 기록하려면? >> 를 사용하자

echo”hello world” >> test.txt

동시에 파일과 화면에 보이는 걸 계속 이어서 기록하려면?

echo”hello world” | tee -a test.txt

standard output(stdou) 과 standard error(stderr)으로 나누어져 있으면?
아래 2개의 다른 output stream을 볼 수 있다. 하나는 stdou이고 다른 하나는 stderr이다.
일반적인 프린트는 stdout를 사용하고, 에러에 관련된 메세지는 보통 stderr를 사용한다.
간단하게 파이썬으로 1개의 stdout을 사용하고 1개의 stderr를 사용하는 스크립트를 만들어보자.

#!/usr/bin/env python

import sys

sys.stdout.write(“I am stdoutn”)
sys.stderr.write(“I am stderrn”)

좋다. 파이썬 스크립드를 sout.py라고 저장하고, 출력을 파일로 redirect 시도해보자.

$ ./sout.py > test.txt

I am stderr
standard output은 redirect가 되었지만, stderr은 그대로 화면으로 보여진다.

stderr을 refirect하고, stdour만 화면에 보여지게 하려면?

./sout.py 2> test.txt

stdout 과 stderr 둘다 파일로 저장하고 싶다면

./sout.py 2&> test.txt

마지막으로, stdout 과 stderr 둘 다 화면과 파일로 동시에 redirect하고 싶다면

./sout.py 2>&1 | tee test.txt

Linux에서 콘솔 내용을 파일로 저장하기”의 1개의 생각

댓글 남기기