Shell – Updating Last Modified Time of a File

filesshelltouch

I have created a script to read 15 pcap files from a folder and merge then into one file using mergecap command. I want the merged file to have the creation time same as the first file of the 15 files and the last modified time same as the last 15th file. W.R.T Changing a file's "Date Created" and "Last Modified" attributes to another file's

I have got how to modify the file times, but this will change all file times to that of the first file. touch -m command needs to be used here , but I cant see how to save the last modified time from the last file and put this to to the merged file.

Best Answer

The simplest : you could use :

touch -r Referencefile  THEFILE  

to give THEFILE the same time as Referencefile so:

rm -f Referencefile
echo > Referencefile  #to set the creation time
#...do your captures here, then concatenate into THEFILE ....
echo >> Referencefile #to set the modification time
touch -r Referencefile THEFILE

But if you prefer to have a more flexible way:

To have a "reliable" way to get the time of a file in a "portable" format, not depending on if the file last changed within 6 months, etc:

tar cf - file  | tar tvf -

so you could do this to get a time suitable for touch:

gettouchdate () { 
 tar cf - "$1" | tar tvf - | tr ':' ' ' \
  | awk '{mm=sprintf("%02d",(match("JanFebMarAprMayJunJulAugSepOctNovDec",$5)+2)/3) ;
          print $10 mm $6 $7 $8 $9 ;}'
}
#firstdate=$(gettouchdate "/path/to/FIRSTFILE")
lastdate=$(gettouchdate "/path/to/LASTFILE")
touch -r /path/to/FIRSTFILE  THEFILE
touch -m "$lastdate" THEFILE
Related Question