1

I tried

stat -c %Y ./* 2>/dev/null | awk -v d="$(date +%s)" 'BEGIN {m=d} $0 < m {m = $0} END {print d - m}'

to find the age of the oldest file in the current directory, and I get a number in seconds with this line.

How do I get a number in days in that one line? Thank you

Luka
  • 11
  • 2
  • Can't you just use days=seconds/(24*60*60) – pLumo Apr 23 '20 at 12:17
  • 1
    why go through all the trouble? ls -t1 | tail -1 will give you the oldest file by modification date. Then you can stat -c %Y that file to get the number of seconds. Divide by 86400 (seconds in a day) to get days. In one line it would be something like echo `stat -c %Y \`ls -t1 | tail -1\``/86400 | bc | tr -d '\n';echo " days" – Fubar Apr 23 '20 at 13:50
  • @Fubar ls will break badly if the names have spaces or glob characters or newlines. See Why *not* parse `ls` (and what to do instead)? – terdon Apr 23 '20 at 14:08
  • if you're worried about garbage filenames, put quotes around the name? file=`ls -t1 | tail -1`;echo `stat -c %Y "$file"`/86400 | bc | tr -d '\n';echo " days" – Fubar Apr 23 '20 at 14:35

2 Answers2

0

If I am not mistaken this solution should also work to print the oldest age in days`without using complicated constructs:

echo "$(( ($(date +%s) - $(stat -c %Y ./* | sort -n | head -n 1)) / 86400 )) days"

and to answer your question - just wrap it for the calculation:

echo $(( $(stat -c %Y ./* 2>/dev/null | awk -v d="$(date +%s)" 'BEGIN {m=d} $0 < m {m = $0} END {print d - m}') /86400 ))
noAnton
  • 361
0

With perl and zsh:

$ ls -ld ./*(D-Om[1])
-rw-r--r-- 1 stephane stephane 205 Jan 11  2004 ./Y2K
$ perl -le 'print -M shift' ./*(D-Om[1])
5947.59262731482

With zsh alone and with nanosecond precision (limited by the precision of your compiler's doubles):

zmodload zsh/datetime zsh/stat
stat -F %s.%N -A t +mtime ./*(D-Om[1]) &&
  print $(((EPOCHREALTIME - t) / 24 / 60 / 60))

(note that a day in that case is a 86400 Unix second unit)