Shell Script – stat

Usually, we have to manipulate the file time attributes in the shell script in order to complete the task. Just like the example at Shell Script – Delete Old Files

# Delete backup files which are more than 90days old 
find ./ -mtime +89 -daystart -type f \( ! -iname "*.sh" \) -exec rm "{}" \;

There are altogether 3 file time attributes
1. Time of Last Access – atime
2. Time of Last Modification –ctime
3. Time of Last Change –mtime

Pay attention to the ctime as it is NOT the creation time of the file. UNIX / Linux filesystem never stores file creation date / time stamp.

The stat command can be used to get the times attributes. The following command shows u the Last Access Time of the file.
stat -c %x <Your File Location>

The following shell script example reads the user input and print the 3 times attributes of the file.

# Read a file from user input and display the time attributes
# of the files

# Read the file location
# "\c" means keep the cursor on the same line
echo "Please input the file location: \c"
read _file

# Quit if the file does not exist
if [ ! -e $_file ]; then
        echo 'Sorry, file does not exist.'
        exit 1

# List the time attributes of the files
echo "Time of last access : $(stat -c %x $_file)"
echo "Time of last modification : $(stat -c %y $_file)"
echo "Time of last change : $(stat -c %z $_file)"

Shell Script To Read File Date
Wikipedia – stat


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

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