Reputation: 489
I'm trying to make a script in bash. This script is supposed to either exit with prompt if file does not exist, or if it does exit it will exit with prompt once modified, or deleted. The parameter $1 is for the filename, and the parameter $2 is for time intervals between each check. Will it be sufficient to use the -N to check whether the file is modified? Code so far(few small errors which im working on):
#!/bin/bash
running=true;
while[ $running ]
do
if [ ! -f $1 ]; then
echo "File: $1 does not exist!"
running=false;
fi
if [ -f $1 ]; then
if [ ! -N $1 ]; then
sleep [ $2 ]
fi;
elif [ -N $1 ]; then
echo "File: $1 has been modified!"
running=false;
fi;
fi;
done;
Upvotes: 1
Views: 951
Reputation: 295472
I'm assuming that you're targeting only platforms with GNU stat installed.
#!/bin/bash
file="$1"
sleep_time="$2"
# store initial modification time
[[ -f $file ]] || \
{ echo "ERROR: $1 does not exist" >&2; exit 1; }
orig_mtime=$(stat --format=%Y "$file")
while :; do
# collect current mtime; if we can't retrieve it, it's a safe assumption
# that the file is gone.
curr_mtime=$(stat --format=%Y "$file") || \
{ echo "File disappeared" >&2; exit 1; }
# if current mtime doesn't match the new one, we're done.
(( curr_mtime != orig_mtime )) && \
{ echo "File modified" >&2; exit 0; }
# otherwise, delay before another time around.
sleep "$sleep_time"
done
That said, in an ideal world, you wouldn't write this kind of code yourself -- instead, you'd use tools such as inotifywait, which operate much more efficiently (being notified by the operating system when things change, rather than needing to periodically check.
Upvotes: 3
Reputation: 121
As an aside - if you change running=false; to exit 1, 2, 3 then the code would be clearer and another script that called this could use the return value to determine why the script completed.
Upvotes: 0
Reputation: 798716
Not precisely. -N
does a comparison between the file's atime and mtime, which is not accurate on e.g. ext3 filesystems that are mounted relatime. You should either use the OS's file monitoring facilities or compare the mtime of the file directly.
Upvotes: 1