![stdout 및 stderr을 출력하고 파일에 쓰는 방법은 무엇입니까? [복사]](https://linux55.com/image/116134/stdout%20%EB%B0%8F%20stderr%EC%9D%84%20%EC%B6%9C%EB%A0%A5%ED%95%98%EA%B3%A0%20%ED%8C%8C%EC%9D%BC%EC%97%90%20%EC%93%B0%EB%8A%94%20%EB%B0%A9%EB%B2%95%EC%9D%80%20%EB%AC%B4%EC%97%87%EC%9E%85%EB%8B%88%EA%B9%8C%3F%20%5B%EB%B3%B5%EC%82%AC%5D.png)
기본적으로 핑 통계를 파일에 쓰고 싶습니다. 지금까지는 이렇게 했지만 ping adress | awk '{ print strftime("[%d.%m.%Y %H:%M:%S]"), $0}' > textfile
이전 프로세스를 중단하지 않고 출력을 볼 수 있으면 더 편리할 것입니다. 나는 또한 이 명령이 내 텍스트 파일에 stderr을 쓰지 않는다는 것을 알고 있습니다. 이 질문을 쓰면서 이 부분이 생각났어요.
명령이나 스크립트는 기본적으로 다음과 같이 동작해야 합니다.
$ command > textfile [15.08.2017 00:17:07] PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data. [15.08.2017 00:17:07] 64 bytes from 8.8.8.8: icmp_seq=1 ttl=44 time=11.5 ms [15.08.2017 00:17:08] 64 bytes from 8.8.8.8: icmp_seq=2 ttl=44 time=11.5 ms ^C $ cat textfile [15.08.2017 00:17:07] PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data. [15.08.2017 00:17:07] 64 bytes from 8.8.8.8: icmp_seq=1 ttl=44 time=11.5 ms [15.08.2017 00:17:08] 64 bytes from 8.8.8.8: icmp_seq=2 ttl=44 time=11.5 ms
답변1
명령을 다음으로 변경합니다.
ping address 2>&1 | awk '{ print strftime("[%d.%m.%Y %H:%M:%S]"), $0}' | tee textfile
2>&1
stderr를 stdout으로 리디렉션하여 화면과 지정된 파일 모두에 출력할 수 있도록 합니다 awk
.tee
awk
출력을 버퍼링하면 짜증이 날 수 있습니다(청크로 표시됨). 그런 다음 다음을 사용하십시오.
awk '{ print strftime("[%d.%m.%Y %H:%M:%S]"), $0; fflush()}'
또는:
stdbuf -oL awk '{ print strftime("[%d.%m.%Y %H:%M:%S]"), $0}'