Search code examples
zshsleepinotifywait

sleep inside inotifywait in a shell function not working


I am trying to run the following function

foo () {
    sleep 1
    echo "outside inotify"
    (inotifywait . -e create |
    while read path action file; do
        echo "test"
        sleep 1
    done)
    echo "end"
}

Until inotifywait it runs correctly; I see:

>> foo
outside inotify
Setting up watches.
Watches established.

However as soon as I create a file, I get

>>> fooo
outside inotify
Setting up watches.
Watches established.
test
foo:6: command not found: sleep
end

Any idea why? Plus do I need to spawn the subprocess ( ) around inotifywait? what are the benefits?

thank you.

Edit I realized I am running on zsh


Solution

  • The read path is messing you up, because unlike POSIX-compliant shells -- which guarantee that only modification to variables with all-uppercase names can have unwanted side effects on the shell itself -- zsh also has special-cased behavior for several lower-case names, including path.

    In particular, zsh presents path as an array corresponding to the values in PATH. Assigning a string to this array will overwrite your PATH as well.