【问题标题】:How can I pass the output from stat to touch?如何将 stat 的输出传递给 touch?
【发布时间】:2018-12-19 15:15:02
【问题描述】:

我在运行 SunOS 5.9 的服务器上有一个 korn shell 脚本,我需要将输出从 stat 传递到 touch 以便在对目录执行某些操作后重置修改后的时间戳,例如

#Get modified timestamp of directory
mtime=$(stat -c %y  ${dirvar})

## Do something to directory that will alter its modified timestamp ##

#Reset modified timestamp of directory
touch -t "${mtime}" "${dirvar}"

我该怎么做?上面的代码返回错误touch: bad time specification

我试过了:

> stat -c %y ${dirvar} | awk '{ split($1, a, "-"); split($2, b, ":"); split(b[3], c, "."); print a[1]a[2]a[3]b[1]b[2]c[1]}'

拿这个:

stat -c %y tmp
2018-12-19 11:28:41.000000000 +0000

输出如下:

20181219112841

但我仍然收到相同的 touch: bad time specification 错误。

【问题讨论】:

    标签: linux shell ksh sunos


    【解决方案1】:

    我从未使用过stat -t,但手册页上写着:

       -t STAMP
              use [[CC]YY]MMDDhhmm[.ss] instead of current time
    

    这意味着,您可以尝试使用以下格式:201812191128.41

    【讨论】:

      【解决方案2】:

      你可以用这个:

      mtime=$(stat -c %Y  ${dirvar})
      touch -d "@${mtime}" "${dirvar}"
      

      它使用 unix 时间戳而不是人类可读的日期,但一些 linux 实用程序接受它。

      【讨论】:

      • 我试过了,但仍然收到 touch: bad time specification 错误。
      • @bad panda:我想我错过了你问题中的 sunos 细节。这适用于 Linux。
      【解决方案3】:

      这会做你想做的事(至少在我的 Linux 机器上):

      MTIME=$( stat now.txt | grep '^Modify:' | awk '{ print $2" "$3 }')
      touch --date "$MTIME" now.txt
      

      或者,如果您无法访问 Linux touch(但有 GNU 日期)(在 so 目录上操作):

      MTIME=$( stat so | grep '^Modify:' | awk '{ print $2" "$3 }')
      TS=$( gdate --date "$MTIME" +%Y%m%d%H%M.%S )
      touch -t $TS so
      

      如果您无权访问 GNU 日期,则必须从 stat 的输出中组装时间戳,例如:

      mtime=$( stat so | grep '^Modify:' | awk '{ print $2" "$3 }')
      yy=$( echo $mtime | cut -f1 -d- )
      MM=$( echo $mtime | cut -f2 -d- )
      DD=$( echo $mtime | cut -f3 -d- | cut -f1 -d\  )
      hhmmss=$(echo $mtime | awk '{ print $2 }' )
      hh=$( echo $hhmmss | cut -f1 -d: )
      mm=$( echo $hhmmss | cut -f2 -d: )
      ss=$( echo $hhmmss | cut -f3 -d: | cut -f1 -d. )
      
      echo ${yy}${MM}${DD}
      echo ${hh}${mm}.${ss}
      
      ts=${yy}${MM}${DD}${hh}${mm}.${ss}
      touch -t $ts so
      

      请记住,设置时间的行为会更改上次更改的时间,因此如果您修改目录并希望回溯目录以避免被发现,则不能使用此技术掩盖您的踪迹。

      【讨论】:

        猜你喜欢
        • 2012-08-29
        • 2011-04-16
        • 2021-02-27
        • 2018-05-15
        • 2020-08-31
        • 1970-01-01
        • 1970-01-01
        • 2020-12-26
        相关资源
        最近更新 更多