Quantcast
Channel: Eureka! » Shell Script
Viewing all articles
Browse latest Browse all 14

Shell Script – stat

$
0
0

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.

#!/bin/sh
# 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
fi

# 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)"

Reference
Shell Script To Read File Date
Wikipedia – stat


Posted in Shell Script Tagged: Linux, Shell Script

Viewing all articles
Browse latest Browse all 14

Trending Articles