Friday, September 05, 2008

Comparing Timestamp Between Two Files

If you need to compare modified time (mtime) of two files, you can use the shell construct:
if [ "myfile1" -nt "myfile2" ]
However, this is only available in Korn and Bash shells. Also it compares only the modified time. If you are used to programming in Bourne shell, you will have to rely on external utilities like Perl/Python/Tcl or others. If you need to compare creation time (ctime), access time (atime) or even compare local file against remote file, below shell function will definitely help you. The "epoch" function will try to return the epoch atime/ctime/mtime of the input file using either Perl, Python or Tcl. It is highly unlikely that any modern UNIX operating system will not have any of these utilities installed.
epoch()
{
 which perl > /dev/null 2>&1
 if [ $? -eq 0 ]; then
  epoch_in_perl $@
  return $?
 fi
 which python > /dev/null 2>&1
 if [ $? -eq 0 ]; then
  epoch_in_python $@
  return $?
 fi
 which tclsh > /dev/null 2>&1
 if [ $? -eq 0 ]; then
  epoch_in_tclsh $@
  return $?
 fi
}

epoch_in_perl()
{
 if [ $# -ne 2 ]; then
  echo "Usage: epoch atime|mtime|ctime file" 1>&2
  return 1
 fi
 if [ ! -e "$2" ]; then
  echo "Error. \"$2\" does not exist" 1>&2
  return 1
 fi
  
 case "$1" in
 atime)
  perl -e '@a=stat("'$2'");print $a[8]'
  ;;
 mtime)
  perl -e '@a=stat("'$2'");print $a[9]'
  ;;
 ctime)
  perl -e '@a=stat("'$2'");print $a[10]'
  ;;
 *)
  echo "Usage: epoch atime|mtime|ctime file" 1>&2
  return 1
  ;;
 esac
}


epoch_in_python()
{
 if [ $# -ne 2 ]; then
  echo "Usage: epoch atime|mtime|ctime file" 1>&2
  return 1
 fi
 if [ ! -e "$2" ]; then
  echo "Error. \"$2\" does not exist" 1>&2
  return 1
 fi
  
 case "$1" in
 atime)
  python -c 'import os.path;print int(os.path.getatime("'$2'"))'
  ;;
 mtime)
  python -c 'import os.path;print int(os.path.getmtime("'$2'"))'
  ;;
 ctime)
  python -c 'import os.path;print int(os.path.getctime("'$2'"))'
  ;;
 *)
  echo "Usage: epoch atime|mtime|ctime file" 1>&2
  return 1
  ;;
 esac
}

epoch_in_tclsh()
{
 if [ $# -ne 2 ]; then
  echo "Usage: epoch atime|mtime|ctime file" 1>&2
  return 1
 fi
 if [ ! -e "$2" ]; then
  echo "Error. \"$2\" does not exist" 1>&2
  return 1
 fi
  
 case "$1" in
 atime)
  echo "file stat \"$2\" a;puts [set a(atime)]" | tclsh
  ;;
 mtime)
  echo "file stat \"$2\" a;puts [set a(mtime)]" | tclsh
  ;;
 ctime)
  echo "file stat \"$2\" a;puts [set a(ctime)]" | tclsh
  ;;
 *)
  echo "Usage: epoch atime|mtime|ctime file" 1>&2
  return 1
  ;;
 esac
}

Here is how you can use this function:

$ epoch mtime myfile1
1201206566

$ epoch atime myfile2
1220593896

$ if [ `epoch ctime myfile1` -lt `epoch ctime myfile2 ]; then
    dosomething
  fi

$ if [ `epoch mtime myfile1` -gt `ssh chihung@remote epoch myfile1` ]; then
    dosomething
  fi

Labels: , , ,

0 Comments:

Post a Comment

<< Home