Linux에서 파일이 변경될 때 명령을 실행하는 방법은 무엇입니까?
작업 디렉터리 내 파일 변화 감지 및 새로운 파일 생성 시 리눅스 명령을 실행하는 방법을 알아보고 싶으신가요? 제대로 찾아오셨습니다.
리눅스에서는 특정 시간에 명령을 실행하도록 스케줄링할 수 있는 cron 기능을 제공합니다.
하지만 파일이 수정되거나 새 파일이 디렉터리에 추가될 때마다 명령을 즉시 실행해야 한다면 어떻게 해야 할까요?
이러한 작업은 생각보다 간단하며, 이를 도와줄 여러 명령줄 도구가 존재합니다.
자, 시작해 볼까요!
watchexec
watchexec은 특정 작업 디렉터리를 감시하고 파일 업데이트 또는 새로운 파일 생성과 같은 변경 사항이 감지되면 명령을 실행하는 유용한 독립형 도구입니다.
주요 특징
- xargs(확장 인수)와 같은 복잡한 명령줄 구문이 필요 없습니다.
- 현재 디렉터리 및 모든 하위 디렉터리의 변경 사항을 실시간으로 감지합니다.
- 특정 언어 런타임에 의존하지 않으며, 특정 언어 또는 생태계와 연결되어 있지 않습니다.
- .gitignore 및 .ignore 파일을 사용하여 감시 대상에서 제외할 파일을 설정할 수 있습니다.
- 프로세스 그룹 기능을 통해 분기된 프로그램 실행을 추적합니다.
- 특정 확장자를 가진 파일만 감시하는 기능도 제공합니다.
- OS X, Linux, Windows 등 다양한 운영체제에서 작동합니다.
- glob 패턴을 기반으로 파일 필터링 및 무시 기능 지원 (파일 이름 일부 검색 가능).
watchexec 설치
watchexec 도구를 간편하게 설치하려면 터미널 또는 쉘 프롬프트에 아래 링크를 입력하고 엔터 키를 누르세요.
리눅스 및 macOS 환경
curl -sS https://webinstall.dev/watchexec | bash
설치가 성공적으로 완료되면 설치 경로가 화면에 표시됩니다. 제 경우에는 /root/.local/bin 경로에 설치되었습니다.
┌──(root💀kali)-[~]
└─# curl -sS https://webinstall.dev/watchexec | bash
Thanks for using webi to install '[email protected]' on 'Linux/x86_64'.
Have a problem? Experience a bug? Please let us know:
https://github.com/webinstall/webi-installers/issues
Lovin' it? Say thanks with a Star on GitHub:
https://github.com/webinstall/webi-installers
Found /root/Downloads/webi/watchexec/cli-v1.18.9/watchexec-1.18.9-x86_64-unknown-linux-musl.tar.xz
Extracting /root/Downloads/webi/watchexec/cli-v1.18.9/watchexec-1.18.9-x86_64-unknown-linux-musl.tar.xz
Installing to /root/.local/opt/watchexec-vcli-v1.18.9/bin/watchexec
Installed 'watchexec vcli-v1.18.9' as /root/.local/bin/watchexec
설치 후, .local/bin 디렉토리로 이동하여 다음 명령으로 파일이 존재하는지 확인하세요.
cd .local/bin ls
다음 단계는 watchexec 도구를 사용할 수 있도록 경로를 설정하는 것입니다.
export PATH="/root/.local/bin:$PATH"
watchexec을 실행하려면 루트 권한으로 터미널에서 watchexec을 입력하세요. watchexec 도구와 함께 사용할 수 있는 플래그와 옵션을 확인하려면 다음 명령을 사용하세요.
watchexec --help
사용 예시
- 해당 디렉토리 또는 하위 디렉토리 내 파일 변경 시 ls -la 명령을 실행합니다. 수정 사항을 감지할 때마다 디렉터리 내 모든 파일을 표시합니다.
watchexec -- ls -la
- 현재 디렉토리 내 python, js, CSS 또는 html 확장자 파일이 변경될 때마다 지정된 명령을 실행합니다. 원하는 명령을 넣을 수 있으며 파일 확장자는 쉼표로 구분합니다.
watchexec --exts py,js,css,html <command>
- lib 또는 src 디렉토리 내 파일 변경 시 특정 명령을 실행합니다. "-w" 옵션은 특정 파일 또는 디렉토리를 감시합니다.
watchexec -w lib -w src <command>
- 현재 디렉토리(및 모든 하위 디렉토리) 내 파일 변경 시 특정 서비스를 호출하거나 재시작합니다.
watchexec -e html -r tor watchexec -e js,py -r mysql
여기서 "-r" 옵션은 시스템에서 실행 중인 프로세스 또는 서비스를 재시작합니다.
watchexec 사용 예시를 더 보려면 공식 GitHub 저장소를 방문하십시오.
entr
entr은 지정된 디렉토리에서 수정 사항 발생 시 임의의 명령을 실행하는 간단하면서도 효과적인 명령줄 유틸리티입니다.
"entr"은 Event Notify Test Runner의 약자입니다. 빠른 피드백과 자동화된 테스트를 목표로 개발되었습니다.
설치 방법
entr은 대부분의 리눅스 배포판에 기본적으로 설치되어 있습니다. 만약 없다면 수동으로 설치해야 합니다.
간단하게 다음 명령으로 설치할 수 있습니다.
sudo apt-get install entr
또는 공식 Git 저장소에서 복제하여 설치할 수도 있습니다.
git clone https://github.com/eradman/entr.git
해당 디렉토리로 이동한 후, 아래 명령을 사용하여 필요한 항목들을 설치합니다.
./configure make test make install
사용 가능한 빌드 옵션을 확인하려면 ./configure -h를 실행하세요.
사용 예시
entr 명령에 사용 가능한 옵션 및 인수를 확인하려면 다음 명령을 사용하세요.
man entr
이 명령은 entr 명령에 대한 사용 설명서를 표시합니다.
NAME
entr — run arbitrary commands when files change
SYNOPSIS
entr [-acdnprsz] utility [argument /_ ...]
DESCRIPTION
A list of files provided on standard input, and the utility is executed using the supplied arguments
if any of them change. entr waits for the child process to finish before responding to subsequent
file system events. A TTY is also opened before entering the watch loop in order to support interac‐
tive utilities.
The arguments are as follows:
-a Respond to all events which occur while the utility is running. Without this option, entr
consolidates events in order to avoid looping. This option has no effect in conjunction with
the -r flag.
-c Clear the screen before invoking the utility specified on the command line. Specify twice to
erase the scroll back buffer.
-d Track the directories of regular files provided as input and exit if a new file is added.
This option also enables directories to be specified explicitly. If specified twice, all new
entries to a directory are recognized, otherwise files with names beginning with ‘.’ are ig‐
nored.
-n Run in non-interactive mode. In this mode entr does not attempt to read from the TTY or
change its properties.
-p Postpone the first execution of the utility until a file is modified.
Manual page entr(1) line 1 (press h for help or q to quit)
- 작업 디렉토리에서 JavaScript 파일이 변경될 때 MySQL 서버를 시작하고 자동으로 다시 로드합니다. 변경 사항이 파일에 저장될 때마다 entr은 MySQL 서버를 다시 로드합니다.
ls *.js | entr -r mysql
- 웹 서버를 자동으로 다시 로드하거나 서버가 종료되면 종료합니다.
$ ls * | entr -rz ./httpd
entr 명령에 대한 자세한 정보와 추가 예시를 보려면 공식 GitHub 저장소를 방문하세요.
마지막으로
이 글이 주어진 디렉토리 내 파일 변경 및 새로운 파일 생성 시 리눅스 명령을 실행하는 방법을 이해하는 데 도움이 되었기를 바랍니다.
리눅스에서 파일 및 디렉토리를 삭제하는 방법에도 관심이 있을 수 있습니다.