brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: inotifywait waits until a file changes, then lets your script go on

Linux
~/tips/tip-linux-inotifywait-watch-folder

inotifywait -m -e close_write /srv/inbox

Blocks until something happens to a file or folder, so a script can react without polling.

Checking a folder every few seconds with a sleep loop works, but it wastes CPU and reacts late. The kernel can just tell you when something changes, and inotifywait is the command-line way to ask.

sudo apt install inotify-tools
inotifywait -m -e close_write /srv/inbox

By default the command exits after the first event. With -m it keeps running and prints one line per event. -e close_write limits it to files that were closed after being opened for writing, which is usually the moment an upload is finished and safe to process.

inotifywait -m -e close_write --format '%w%f' /srv/inbox | while read -r f; do echo "new file: $f"; done

The --format option cuts the output down to the path, which is easier to feed to a loop.

Two caveats from the man page. The close_write event does not prove any bytes were written, only that a writable handle was closed. And inotify watches a folder, not the subfolders below it, unless you add -r. Watching a very large tree recursively can hit the kernel limit on watches, so keep the watched folder small. A sleep loop is still fine for a one-off job, but for anything that runs all day this is gentler on the machine.

Further reading: inotifywait(1) manual

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link