watch 명령어로 실시간 변화하는 파일의 내용 확인하기

 

명령어: watch
키워드: 실시간 파일 변동 확인
사용처: 리눅스에서 파일내 변경 진행 중인 내용을 확인 하고 싶을 때

리눅스에서 watch 명령어를 통해 리눅스에서 실시간으로 변경중인 파일의 내용을 확인할 수 있습니다. 가령 bonding을 구성한다든지, 시스템의 uptime 등 시시각각 변경되는 내용을 watch 명령어로 확인할 수 있습니다. watch 명령어의 버전에 따라 옵션이 조금 다를 수 있습니다. 아래와 같이 watch --help 를 입력해 보세요.

Linux watch –help 옵션

Usage:
 watch [options] command

Options:
  -b, --beep             beep if command has a non-zero exit
  -c, --color            interpret ANSI color and style sequences
  -d, --differences[=<permanent>]
                         highlight changes between updates
  -e, --errexit          exit if command has a non-zero exit
  -g, --chgexit          exit when output from command changes
  -n, --interval <secs>  seconds to wait between updates
  -p, --precise          attempt run command in precise intervals
  -t, --no-title         turn off header
  -w, --no-wrap          turn off line wrapping
  -x, --exec             pass command to exec instead of "sh -c"

 -h, --help     display this help and exit
 -v, --version  output version information and exit

옵션 없이 사용할 경우 watch는 지정된 명령을 2초마다 실행합니다.

   

1. uptime 파일의 변화를 5초 간격으로 화면에 출력

uptime 값을 실시간으로 아래와 같이 확인할 수 있으며, 변경된 부분은 -d 옵션으로 하이라이트 됩니다. 여기서는 하이라이트를 표시할 수 없어 내용만 입력하였습니다.

# watch -d -n 5 'cat /proc/uptime'

Every 5.0s: c...  ip-172-26-4-87.ap-northeast-2.compute.internal: Wed Oct  4 16:07:39 2023

5369148.46 10669117.07

   

2. bond0 파일의 변화를 1초 간격으로 화면에 출력

본딩 구성하여 아래와 같이 watch 명령어로 모니터링을 하고 있다가 네트워크 장애 테스트시 변화 내용을 확인할 수 있습니다. 케이블을 절체하여 네트워크 이중화가 제대로 동작하는지 확인해 보세요.

# watch -d -n 1 'cat /proc/net/bonding/bond0'

Ethernet Channel Bonding Driver: v3.7.1 (April 27, 2011)

Bonding Mode: load balancing (round-robin)
MII Status: up
MII Polling Interval (ms): 100
Up Delay (ms): 0
Down Delay (ms): 0

Slave Interface: ens2f0
MII Status: up
Speed: 1000 Mbps
Duplex: full
Link Failure Count: 0
Permanent HW addr: b4:96:91:a3:2d:fe
Slave queue ID: 0

Slave Interface: ens4f0
MII Status: up
Speed: 1000 Mbps
Duplex: full
Link Failure Count: 0
Permanent HW addr: b4:96:91:a3:2e:b0
Slave queue ID: 0

   

3. 실시간 시간 확인

watch 명령어로 시간을 실시간으로 출력할 수 있습니다.

# watch -n 1 date

Every 1.0s: date  ip-172-26-4-87.ap-northeast-2.compute.internal: Thu Oct  5 09:01:09 2023

Thu Oct  5 09:01:09 KST 2023

watch 명령어를 이용하여 리눅스의 다양한 시스템을 모니터링 해보세요.