1

I'm trying to read the number of lines in a file, and the last modification date of that file (e.g. if it was last modified Jan 18, 2013, it should output 2013-01-18), then append the data to the given input file in the form theFile: 4 lines, modified on 2013-01-18. I tried to store both pieces of data in their own variables before outputting with echo.

#!/bin/sh
totLines=$(wc -l < $1)
modDate=$(date -r $1)
echo $1: $totLines "lines, modified on" $modDate >> $1

Is my method of finding the last modification date correct? I was told that it is, but I can't figure out why, since I can't find any information on what date -r does and I can't get it working in any script I try out. There's also using stat, but I can't get that working either with stat -c %y $1 where I get stat: illegal option -- c

Adam
  • 293

1 Answers1

3

Both date -r and this flavour of stat are GNU specific. Maybe you were told them by a Linux user and you're using another system.

Unfortunately, there's no standard command to get that information reliably. The most portable you could get would be:

modDate=$(perl -MPOSIX -le '@s=stat shift or die$!;
  print strftime "%Y-%m-%d", localtime $s[9]' -- "$1") || exit

zsh has its own builtin stat command:

zmodload zsh/stat
zstat -F %F +mtime -- "$1"

(those two commands above, for symlinks, would return the modification time of the target of the symlink like GNU date -r would, if you want the time of the symlink (like in you GNU stat command), change stat to lstat in the perl solution, or add -L to zstat).

Also, you forgot the double quotes around your variables and you shouldn't use echo for arbitrary data.