Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test a file date with bash

I am trying to test how old ago a file was created (in seconds) with bash in an if statement. I need creation date, not modification.

Do you have any idea how to do this, without using a command like find with grep?

like image 832
JeffPHP Avatar asked Nov 30 '09 11:11

JeffPHP


People also ask

How to use `date` command in Bash?

Bash uses `date ` command to display or change the current date and time value of the system. Date and time value can be printed in different formats by using this command. This command can also be used for calculating date and time value related tasks. `date` command without any option just prints the current system’s date and time value.

What is the use of test in Bash?

On Unix-like operating systems, test is a builtin command of the Bash shell that tests file attributes, and perform string and arithmetic comparisons. test provides no output, but returns an exit status of 0 for "true" (test successful) and 1 for "false" (test failed).

How to create a file with the current time in Bash?

#!/bin/bash d="$ (date +%Y-%m-%d_%HZZZ.tmp.txt)" touch "$d" printf "%s " *.txt | LC_ALL=C sort | awk -v d="$d" 'f {print} d==$0 {f=1}' rm "$d" This creates a name that matches the current time. This creates a file with name matching the current time.

How do I test if a file exists in Bash?

File test operators let you test various aspects of a file like if a file exists, is readable/writable, etc. Using file test operators can help to prevent errors in your Bash scripts. The code below is a boilerplate for the if statement. The if-else statement is a powerful tool you’ll often see in Bash scripts.


1 Answers

I'm afraid I cann't answer the question for creation time, but for last modification time you can use the following to get the epoch date, in seconds, since filename was last modified:

date --utc --reference=filename +%s

So you could then so something like:

modsecs=$(date --utc --reference=filename +%s)
nowsecs=$(date +%s)
delta=$(($nowsecs-$modsecs))
echo "File $filename was modified $delta secs ago"

if [ $delta -lt 120 ]; then
  # do something
fi

etc..

Update A more elgant way of doing this (again, modified time only): how do I check in bash whether a file was created more than x time ago?

like image 160
Joel Avatar answered Sep 22 '22 06:09

Joel