Swandrew
Swandrew

Reputation: 73

Identifying when a file is changed- Bash

So in my bash shell script, I have it running through a for loop. Inside the for loop, I use find "$myarray[i]" >> $tmp to look for a certain directory each time through the loop. Sometimes, it finds the variable in myarray[i] and sometimes it doesn't. When it does find something in myarray[i], I want it to execute echo "<br>" >> $tmp. Is there a way for me to check whether $tmp has changed after executing the find line, so that I know when to execute the echo "<br>" >> $tmp line?

Upvotes: 1

Views: 83

Answers (2)

willdye
willdye

Reputation: 793

If your objective is to take action whenever a filesystem event happens (such as a file update or directory creation), I'd avoid writing a custom polling loop. Instead, use one of several tools created specifically for that use case.

The Linux tool "inotify" seems to be popular, and it has wrappers such as inotify-tools to make it easier to call from a command line. There's also the cross-platform Python package "watchdog", the .NET/mono tool "System.IO.FileSystemWatcher", the OSX built-in utility "Folder Actions", "fswatch", and others.

It's easy to mess up polling, and hard to properly handle things like automatic restarts, unusual file names, and filesystem errors. The purpose-specific tools were created because there's no good way to do it with a (simple) bash loop.

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 247210

I would store the output of find, and if non-empty, echo the line break:

found=$(find . -name "${myarray[i]}")
if [[ -n $found ]]; then
    { echo "$found"; echo "<br>"; } >> "$tmp"
fi

Upvotes: 1

Related Questions