Is it possible to clear a file preserving its timestamp, using standard Linux commands? For example:
echo "" > file-name
converts the text file to empty, this is OK for me. But I need to keep the timest开发者_Go百科amp unchanged.
You can do the following using touch:
#!/bin/sh
TMPFILE=`mktemp`
#save the timestamp
touch -r file-name $TMPFILE
> file_name
#restore the timestamp after truncation
touch -r $TMPFILE file-name
rm $TMPFILE
You can skip the tmp file by using date to record the time stamp string and pass it back to touch.
#!/bin/sh
# Save the timestamp
STAMP=`date -r file_name`
> file_name
# Restore the timestamp
touch -d "$STAMP" file_name
Here is the nice article. Hope it help.
ADDED:
Sorry, just read, that you need the zero file, not the copy. Touch could create zero files with needed time stamps.
Example
To set the date to 7:30 am 1st October 2015
touch /t 2015 10 01 07 30 00 MyFile.txt
To supplement mmond's answer (can't comment due to insufficient reputation), don't forget about localization. To work with any localization, the answer should read:
#!/bin/sh
# Save the timestamp
STAMP=`LANG= date -r file_name`
> file_name
# Restore the timestamp
touch -d "$STAMP" file_name
精彩评论