Clear file without changing its timestamp

Is it possible to clear a file by saving its timestamp using standard Linux commands? For instance:

echo ""> file name

converts a text file to empty, this is normal for me. But I need to keep the timestamp unchanged.

+3
source share
4 answers

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
+7
source

You can skip the tmp file using the date to write the time stamp string and transfer it back.

#!/bin/sh
# Save the timestamp
STAMP=`date -r file_name`
> file_name
# Restore the timestamp
touch -d "$STAMP" file_name
+2
source

. , .

:

, , , . Touch .

   To set the date to 7:30 am 1st October 2015
   touch /t 2015 10 01 07 30 00 MyFile.txt
+1

To add mmond's answer (you can not comment due to insufficient reputation), do not forget about localization. To work with any localization, the answer should look like this:

#!/bin/sh
# Save the timestamp
STAMP=`LANG= date -r file_name`
> file_name
# Restore the timestamp
touch -d "$STAMP" file_name
0
source

Source: https://habr.com/ru/post/1747332/


All Articles