file-name" />
开发者

Clear a file without changing its timestamp

开发者 https://www.devze.com 2023-01-01 09:57 出处:网络
Is it possible to clear a file preserving its timestamp, using standard Linux commands? For example: echo \"\" > file-name

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
0

精彩评论

暂无评论...
验证码 换一张
取 消