본문 바로가기
IT/Linux

리눅스 표준 출력과 표준 에러를 한 파일에 리다이렉션 하기

by 뉴코딩맨 2023. 3. 28.
리눅스에서 표준 출력과 표준 에러를 한 파일에 리다이렉션 할 수 있습니다. 명령어에 이상이 없다면 표준 출력이 작동해서 결과가 파일에 출력 될 것이고 명령어에 이상이 있다면 표준 에러가 작동해서 에러 메시지가 파일에 출력 될 것입니다.
 

첫 번째 방법

 

user@user-virtual-machine:~$ ls -l > output.txt 2> output.txt
user@user-virtual-machine:~$ cat output.txt 
total 36
drwxr-xr-x 2 user user 4096  2월  8 21:04 Desktop
drwxr-xr-x 2 user user 4096  2월  8 21:04 Documents
drwxr-xr-x 2 user user 4096  2월  8 21:04 Downloads
drwxr-xr-x 2 user user 4096  2월  8 21:04 Music
-rw-rw-r-- 1 user user    0  3월 28 18:32 output.txt
drwxr-xr-x 2 user user 4096  2월  8 21:04 Pictures
drwxr-xr-x 2 user user 4096  2월  8 21:04 Public
drwx------ 3 user user 4096  2월  8 21:04 snap
drwxr-xr-x 2 user user 4096  2월  8 21:04 Templates
drwxr-xr-x 2 user user 4096  2월  8 21:04 Videos
user@user-virtual-machine:~$ ls -l7 > output.txt 2> output.txt
user@user-virtual-machine:~$ cat output.txt 
ls: invalid option -- '7'
Try 'ls --help' for more information.

 

출력 리다이렉션 다음에 에러 리다이렉션을 사용해서 동일한 파일에 표준 출력, 표준 에러를 리다이렉션을 할 수 있습니다.

 

두 번째 방법

 

user@user-virtual-machine:~$ ls -l > output.txt 2>&1
user@user-virtual-machine:~$ cat output.txt 
total 36
drwxr-xr-x 2 user user 4096  2월  8 21:04 Desktop
drwxr-xr-x 2 user user 4096  2월  8 21:04 Documents
drwxr-xr-x 2 user user 4096  2월  8 21:04 Downloads
drwxr-xr-x 2 user user 4096  2월  8 21:04 Music
-rw-rw-r-- 1 user user    0  3월 28 18:34 output.txt
drwxr-xr-x 2 user user 4096  2월  8 21:04 Pictures
drwxr-xr-x 2 user user 4096  2월  8 21:04 Public
drwx------ 3 user user 4096  2월  8 21:04 snap
drwxr-xr-x 2 user user 4096  2월  8 21:04 Templates
drwxr-xr-x 2 user user 4096  2월  8 21:04 Videos
user@user-virtual-machine:~$ ls -l7 > output.txt 2>&1
user@user-virtual-machine:~$ cat output.txt 
ls: invalid option -- '7'
Try 'ls --help' for more information.

 

2>&1을 사용해서 동일한 파일에 표준 출력, 표준 에러를 리다이렉션을 할 수 있습니다.

 

 

세 번째 방법

 

user@user-virtual-machine:~$ ls -l &> output.txt
user@user-virtual-machine:~$ cat output.txt 
total 36
drwxr-xr-x 2 user user 4096  2월  8 21:04 Desktop
drwxr-xr-x 2 user user 4096  2월  8 21:04 Documents
drwxr-xr-x 2 user user 4096  2월  8 21:04 Downloads
drwxr-xr-x 2 user user 4096  2월  8 21:04 Music
-rw-rw-r-- 1 user user    0  3월 28 18:35 output.txt
drwxr-xr-x 2 user user 4096  2월  8 21:04 Pictures
drwxr-xr-x 2 user user 4096  2월  8 21:04 Public
drwx------ 3 user user 4096  2월  8 21:04 snap
drwxr-xr-x 2 user user 4096  2월  8 21:04 Templates
drwxr-xr-x 2 user user 4096  2월  8 21:04 Videos
user@user-virtual-machine:~$ ls -l7 &> output.txt
user@user-virtual-machine:~$ cat output.txt 
ls: invalid option -- '7'
Try 'ls --help' for more information.
user@user-virtual-machine:~$ ls -l7 &>> output.txt
user@user-virtual-machine:~$ cat output.txt 
ls: invalid option -- '7'
Try 'ls --help' for more information.
ls: invalid option -- '7'
Try 'ls --help' for more information.

 

&>를 사용해서 동일한 파일에 표준 출력, 표준 에러를 리다이렉션 할 수 있습니다.

댓글