Shell Script – Check if a file is updated

In the housekeeping shell script, i would update some files. The following example will try to update the /tmp/test file and display the result.

#!/bin/sh
# Update /tmp/test and check whether it is updated
# successfully

# Get the start time in second
_startTimeInSecond=$(date +%s)

# Create the test file if it does not exist
if [ ! -e '/tmp/test' ]; then
        echo "This file is created on $_startTimeInSecond" > '/tmp/test'
fi

# Comment the following line if u want -ve result
echo "This file is updated on $_startTimeInSecond" >> '/tmp/test'

# Check whether the file is updated
_fileModifiedTime=$(stat -c %Y /tmp/test)
if [ "$(expr $_fileModifiedTime - $_startTimeInSecond)" -ge 0 ]; then
        echo "/tmp/test is UPDATED"
else
        echo "/tmp/test is NOT UPDATED"
fi

Done =)

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.