代码之家  ›  专栏  ›  技术社区  ›  Alex F

清除文件而不更改其时间戳

  •  3
  • Alex F  · 技术社区  · 16 年前

    是否可以使用标准Linux命令清除保留时间戳的文件?例如:

    回音“>文件名

    4 回复  |  直到 16 年前
        1
  •  7
  •   Hasturkun    16 年前

    您可以使用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
    
        2
  •  3
  •   mmond    13 年前

    您可以跳过tmp文件,方法是使用date记录时间戳字符串并将其传递回touch。

    #!/bin/sh
    # Save the timestamp
    STAMP=`date -r file_name`
    > file_name
    # Restore the timestamp
    touch -d "$STAMP" file_name
    
        3
  •  1
  •   mosg    16 年前

    Here

    补充:

    触摸

    例子

       To set the date to 7:30 am 1st October 2015
       touch /t 2015 10 01 07 30 00 MyFile.txt
    
        4
  •  0
  •   Alex Potapenko    11 年前

    补充 蒙德 的答案(由于声誉不足,无法评论),不要忘记本地化。要使用任何本地化,答案应为:

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