top 명령어를 스크립트에서 사용할 때 특수 문자가 포함되는 현상에 대한 원인과 해결 방안에 대해서 다룹니다.
문제
스크립트로 top 명령어 실행 결과를 저장 후 가공하기 위한 작업을 할 때 vim 편집기로 파일을 열어보면 이상한 문자가 섞여서 나오는 부분을 확인할 수 있습니다.
[root@rhel92 ~]# top -n 2 | grep Cpu > test.txt
[root@rhel92 ~]# vim test.txt
%Cpu(s):^[(B^[[m^[[39;49m^[[1m 0.0 ^[(B^[[m^[[39;49mus,^[(B^[[m^[[39;49m^[[1m 3.1 ^[(B^[[m^[[39;49msy,^[(B^[[m^[[39;49m^[[1m 0.0 ^[(B^[[m^[[39;49mni,^[(B^[[m^[[39;49m^[[1m 96.9 ^[(B^[[m^[[39;49mid,^[(B^[[m^[[39;49m^[[1m 0.0 ^[(B^[[m^[[39;49mwa,^[(B^[[m^[[39;49m^[[1m 0.0 ^[(B^[[m^[[39;49mhi,^[(B^[[m^[[39;49m^[[1m 0.0 ^[(B^[[m^[[39;49msi,^[(B^[[m^[[39;49m^[[1m 0.0 ^[(B^[[m^[[39;49mst^[(B^[[m^[[39;49m^[(B^[[m^[[39;49m^[[K
%Cpu(s):^[(B^[[m^[[39;49m^[[1m 3.2 ^[(B^[[m^[[39;49mus,^[(B^[[m^[[39;49m^[[1m 3.8 ^[(B^[[m^[[39;49msy,^[(B^[[m^[[39;49m^[[1m 0.0 ^[(B^[[m^[[39;49mni,^[(B^[[m^[[39;49m^[[1m 92.7 ^[(B^[[m^[[39;49mid,^[(B^[[m^[[39;49m^[[1m 0.0 ^[(B^[[m^[[39;49mwa,^[(B^[[m^[[39;49m^[[1m 0.2 ^[(B^[[m^[[39;49mhi,^[(B^[[m^[[39;49m^[[1m 0.2 ^[(B^[[m^[[39;49msi,^[(B^[[m^[[39;49m^[[1m 0.0 ^[(B^[[m^[[39;49mst^[(B^[[m^[[39;49m^[(B^[[m^[[39;49m^[[K
하지만 동일한 파일을 cat 명령으로 열어보면 정상적으로 출력이 됩니다.
[root@rhel92 ~]# cat test.txt
%Cpu(s): 0.0 us, 3.1 sy, 0.0 ni, 96.9 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
%Cpu(s): 3.2 us, 3.8 sy, 0.0 ni, 92.7 id, 0.0 wa, 0.2 hi, 0.2 si, 0.0 st
근본 원인
test.txt 파일의 정보를 살펴보면 일반 텍스트와 다르게 “with escape sequences”라는 문구가 출력되는 걸 볼 수 있는데 top 명령어가 ANSI Escape Sequences를 사용하여 텍스트 출력의 색상, 스타일 등을 제어하기 위한 기능이 추가되어 있기 때문입니다.
[root@rhel92 ~]# file test.txt
test.txt: ASCII text, with very long lines, with escape sequences
ANSI 이스케이프 시퀀스(ANSI escape sequences)는 비디오 텍스트 터미널 및 터미널 에뮬레이터에서 커서 위치, 색, 글꼴 스타일, 그 밖의 옵션을 제어하는 대역 내 신호 방식을 위한 표준이다. 대부분 ASCII 이스케이프 문자와 괄호 문자로 시작하는 특정 바이트 시퀀스들은 텍스트에 임베디드된다. 터미널은 이 시퀀스들을 텍스트가 아닌 명령으로 해석한다.
해결
top 명령어는 이런 상황에 대비해 -b 옵션을 제공하고 있습니다. -b 옵션을 사용하면 배치 모드에서 top을 실행하며 다른 곳으로 출력을 전달하는데 유용하다고 man 페이지에 소개되어 있습니다.
[root@rhel92 ~]# man top
...
-b :Batch-mode operation
Starts top in Batch mode, which could be useful for sending output from top to other programs or
to a file. In this mode, top will not accept input and runs until the iterations limit you've
set with the `-n' command-line option or until killed.
결과적으로 -b 옵션을 주면 위와 같은 문제가 해소되며 top 결과를 자유롭게 가공하여 사용할 수 있습니다.
[root@rhel92 ~]# top -b -n 2 | grep Cpu > test.txt
[root@rhel92 ~]# vim test.txt
%Cpu(s): 0.0 us, 5.9 sy, 0.0 ni, 94.1 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
%Cpu(s): 0.2 us, 0.0 sy, 0.0 ni, 99.8 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
참조
https://stackoverflow.com/questions/9927284/top-command-special-characters-in-shell-script