如何将统计信息的输出传递给touch?

时间:2018-12-19 15:15:02

标签: linux shell ksh sunos

我在运行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错误。

3 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

这将满足您的要求(至少在我的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

请记住,设置时间的操作会更改上次更改的时间,因此,如果您修改目录并希望为目录加日期以避免检测,则您不能使用此技术来覆盖曲目。

答案 2 :(得分:0)

您可以使用此:

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

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