简体   繁体   中英

Why does my bash for loop hang at a command?

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, ie, 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. Eg, 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM