17

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?

whoan
  • 8,143
  • 4
  • 39
  • 48
JeffPHP
  • 271
  • 1
  • 2
  • 9
  • There are a number of commands you can use to do this and bash can call all of them. Why the aversion to using external commands? UNIX was built on the philosophy of tools doing one thing and one thing well. – paxdiablo Nov 30 '09 at 11:25
  • will last modifiction time suffice - or do you need creation time? – Joel Nov 30 '09 at 11:26
  • I'd prefer creation time – JeffPHP Nov 30 '09 at 17:55
  • creation time isn't stored anywhere...so unless you store it yourself last modified is the best your going to get i'm afraid. – Joel Dec 01 '09 at 09:55
  • Date of creation isn't stored on many often used filesystems. What filesystem do you use? – Martin Nov 30 '09 at 11:49
  • The problem would also be to get the time with standard tools that operate above VFS, no matter if the timestamp is stored or not. +1 for the only valid answer about creation timestamps... – TheBonsai Nov 30 '09 at 13:14
  • Ext2FS / ReiserFS (Linux/Debian) – JeffPHP Nov 30 '09 at 17:17

4 Answers4

24

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?

Community
  • 1
  • 1
Joel
  • 29,538
  • 35
  • 110
  • 138
8

Here is the best answer I found at the time being, but it's only for the modification time :

expr `date +%s` - `stat -c %Y /home/user/my_file`
JeffPHP
  • 271
  • 1
  • 2
  • 9
2

If your system has stat:

modsecs=$(stat --format '%Y' filename)

And you can do the math as in Joel's answer.

Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
1

you can use ls with --full-time

file1="file1"
file2="file2"
declare -a array
i=0
ls -go --full-time "$file1" "$file2" | { while read -r  a b c d time f
do    
  time=${time%.*}  
  IFS=":"
  set -- $time
  hr=$1;min=$2;sec=$3
  hr=$(( hr * 3600 ))
  min=$(( min * 60 ))  
  totalsecs=$(( hr+min+sec ))
  array[$i]=$totalsecs  
  i=$((i+1))
  unset IFS      
done
echo $(( ${array[0]}-${array[1]} ))
}  
ghostdog74
  • 327,991
  • 56
  • 259
  • 343