Score:1

How do I monitor a directory for changes and run a command automatically? (CLI)

bd flag

I would like to monitor a directory for changes (new files, subdirectories, or changed files or subdirectories). As soon as a change has been detected, I want the passed command to be called. It should continue to monitor for changes and run the command, until the command is killed using ctrl-c.

For example:

$ cd directoryname
$ watchcommand examplecommand arg1 arg2 arg3
...
... change detected in example1.txt, running "examplecommand arg1 arg2 arg3"
...
... change detected in example2.txt, running "examplecommand arg1 arg2 arg3"

I know there are similar questions out there to this question. However, they have not been marked as duplicates of each other, because they all differ in what the user wants to happen once a change has been detected. This question is meant to be more generic. I'm interested in running a placeholder command once changes are detected.

Please post one answer per tool, so that each tool can be voted on separately.

Raffa avatar
jp flag
Like this: https://askubuntu.com/a/1443575/968501 ?
bd flag
@Raffa That question is closed as a duplicate of a question that asks about how to copy a file to multilpe directories, which is not what this question is about.
bd flag
I'm trying to create a canonical question for just the "watch a folder for changes (including changes within a file)".
Raffa avatar
jp flag
No, not the question ... My answer :-) ... I thought I linked to the answer.
Raffa avatar
jp flag
That also can be done with `inotifywait`
bd flag
@Raffa Your answer is definitely helpful. If you want to post an answer about inotifywait here, I'll be glad to upvote and accept. But I want to have a canonical question that is open to other alternative answers.
hr flag
... see also [Bash script to monitor file change and execute command](https://askubuntu.com/questions/819265/bash-script-to-monitor-file-change-and-execute-command) and [Monitor folder contents changes](https://askubuntu.com/questions/541128/monitor-folder-contents-changes)
bd flag
@steeldriver Thanks. That first one is a duplicate. I've cast a close vote on my own question.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.