Reputation: 488
My question is how to detect a file that has entered the directory the last. (not with creation/modification timestamp)
Usecase: My scripts must use the files that has been restored from a backup. (if relevant the restoration process takes about 10 minutes). But this file is not necessarily the LATEST in directory. EG:
-rw-rw-r--. 1 user user 670660 Oct 25 09:21 file1
-rw-r--r--. 1 user user 0 Oct 29 11:00 file3
-r--r--r--. 1 user user 37031332 Oct 29 11:56 file4 # <--the LATEST file
-rw-r--r--. 1 user user 0 Oct 30 12:00 file5
-rwx------. 1 user user 6980628 Oct 31 12:47 file6
It is possible that the same file already existed in the directory, and been overridden. The solution i'm looking for should detect this case as well.
P.S. - timestamp options always take me to the NEWEST (or last modified) file. Not my case. Thanks.
Upvotes: 2
Views: 303
Reputation: 18697
If you don't have to determine the last file that entered the directory after the fact, but can afford to monitor the directory continuously, you could use the Linux kernel's inotify
API, and the inotifywait
tool from the inotify-tools
.
In your case, you'll want to monitor the moved_to
and created
events:
inotifywait -q -m -e moved_to -e create --format %f /path/to/dir |
while IFS= read -r file; do
echo "last file that entered dir: $file"
done
In case you can wrap your backup restore procedure with some setup and teardown code, you could start monitoring the target dir with inotifywait
just before backup restore, and then stop & read the last file that entered the target after restore finishes.
A simple demo, where backup restore is replaced with manual file creation:
#!/bin/bash
# target dir, assuming it exists
dir=/tmp/bucket
# setup $dir monitoring in background
list=$(mktemp)
coproc inotifywait -q -m -e moved_to -e create --format %f "$dir" >"$list"
# kill the monitor on backup restore done, and/or on script exit
wrapup() {
[[ $COPROC_PID ]] && kill -INT "$COPROC_PID" && last=$(tail -n1 "$list") && rm "$list"
}
trap 'wrapup' USR1 EXIT
# simulated "restore from backup" to $dir
rm -f "$dir/xyz"; touch "$dir/xyz"
# kill the monitor, read the last file, and clean-up
kill -USR1 $$
# do something with that last file
echo "Last file in $dir was $last"
Upvotes: 2