Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a shell script when a file or directory changes?

I want to run a shell script when a specific file or directory changes.

How can I easily do that?

like image 559
Drew LeSueur Avatar asked Oct 30 '10 19:10

Drew LeSueur


People also ask

How do you run the command every time a file is modified in Linux?

Call ls -la when any file changes in this directory/subdirectory. This command shows all the files present in the directory whenever it detects any modification.

How do I run a sh file from a different directory?

To use full path you type sh /home/user/scripts/someScript . sh /path/to/file is different from /path/to/file . sh runs /bin/sh which is symlinked to /bin/dash . Just making something clear on the examples you see on the net, normally you see sh ./somescript which can also be typed as `sh /path/to/script/scriptitself'.

How will you monitor file change in Linux?

In Linux, the default monitor is inotify. By default, fswatch will keep monitoring the file changes until you manually stop it by invoking CTRL+C keys. This command will exit just after the first set of events is received. fswatch will monitor changes in all files/folders in the specified path.

What does $$ do in shell?

The $$ variable is the PID (Process IDentifier) of the currently running shell. This can be useful for creating temporary files, such as /tmp/my-script. $$ which is useful if many instances of the script could be run at the same time, and they all need their own temporary files.


2 Answers

You may try entr tool to run arbitrary commands when files change. Example for files:

$ ls -d * | entr sh -c 'make && make test' 

or:

$ ls *.css *.html | entr reload-browser Firefox 

or print Changed! when file file.txt is saved:

$ echo file.txt | entr echo Changed! 

For directories use -d, but you've to use it in the loop, e.g.:

while true; do find path/ | entr -d echo Changed; done 

or:

while true; do ls path/* | entr -pd echo Changed; done 
like image 169
kenorb Avatar answered Oct 12 '22 22:10

kenorb


I use this script to run a build script on changes in a directory tree:

#!/bin/bash -eu DIRECTORY_TO_OBSERVE="js"      # might want to change this function block_for_change {   inotifywait --recursive \     --event modify,move,create,delete \     $DIRECTORY_TO_OBSERVE } BUILD_SCRIPT=build.sh          # might want to change this too function build {   bash $BUILD_SCRIPT } build while block_for_change; do   build done 

Uses inotify-tools. Check inotifywait man page for how to customize what triggers the build.

like image 20
Dominykas Mostauskis Avatar answered Oct 12 '22 22:10

Dominykas Mostauskis