abergmeier
abergmeier

Reputation: 14042

How to exit from inotifywait

I want to monitor a given directory until a certain condition arises.

ARCHIVE_PATH=$(inotifywait -m -r -q -e close_write -e moved_to --format '%w%f' /test | while read FILE; do
  # ... Code ...
  if [ $CONDITION ]; then
    echo "$VALUE"
    break
  fi
done)

Now, no matter whether I use break or exit 0, the while loop will continue. What is the best way of exiting the loop and passing the output to the variable, then?

EDIT:

Replacing break with kill -2 $$ seems to only trigger a continue. And even worse - there are times, when break works fine - but rarely.

Upvotes: 2

Views: 2686

Answers (2)

dgo.a
dgo.a

Reputation: 2764

Try this: kill -2 -$$ or kill -SIGINT -$$

The minus sign in -$$ sends the signal to all the processes in the group. The $$ is the current process. So -$$ should mean: send this signal to all the processes in the group of the current process.

This man page explains more: http://linux.die.net/man/1/kill

The answer was inspired from: https://bbs.archlinux.org/viewtopic.php?id=186989

Upvotes: 1

abergmeier
abergmeier

Reputation: 14042

I now do this by signalling:

trap "exit 0" 10

ARCHIVE_PATH=$(inotifywait -m -r -q -e close_write -e moved_to --format '%w%f' /test | while read FILE; do
  # ... Code ...
  if [ $CONDITION ]; then
    echo "$VALUE"
    kill 10 $$
  fi
done)

Seems like the shell is not allowing SIGINT to be sent from a subshell or so, thus I had to send another signal (SIGUSR1) and trap it.

Upvotes: 0

Related Questions