I am using entr to check if new files are added to certain subdirectories, and run a command if such an event occurs. If I have a directory with folders: folder
, prefix_folder1
, and prefix_folder2
, then I want to monitor the presence of new files within a certain subdirectory in the latter two, i.e., monitor prefix_folder1/subdir
and prefix_folder2/subdir
This is my current approach with an infinite loop:
1 #!/bin/bash
2
3 trap "exit" INT # in case of ^C
4 while true
5 do
6 for stage in $(ls '/Users/me/test')
7 do
8 if [[ "$stage" == "prefix"* ]]; then #check for prefix
9 ls -d * /Users/me/test/$stage/subdir | entr -pd echo hey
10
11 fi
12 done
13 done
However for each directory, the script hangs at line 9 until a new file is created. E.g., if it is at prefix_folder2/subdir
it will not echo
"hey" if a file is created in prefix_folder1/subdir
.
My understanding of bash for loops is limited in this scenario and I'm not sure what keywords to look up to find a solution for this.
CodePudding user response:
I think this is what you want:
while true
do
ls -d /Users/me/test/prefix*/subdir | entr -pd echo hey
done
This will pass all the directories you want to monitor at once to a single invocation of entr
, rather than calling it separately for each directory.
You don't need to include *
in the ls
command, as that will also monitor all the files in the current directory.