检查上次使用的 .sh 文件

And*_*ejs 7 executable timestamps files atime

当您运行时./myscript.sh,这是否被视为“访问”时间?

我需要知道上次运行脚本的时间,但我不确定这是否算作mtime,ctimeatime此处描述的差异)。

ter*_*don 16

正如您链接到的答案所述,这取决于您的设置。原则上,atime每次读取文件时都会更改,为了运行脚本,您需要读取它。所以是的,通常,atime每次执行脚本时都会改变。这可以通过检查当前时间、运行脚本然后再次检查来轻松演示:

$ printf '#!/bin/sh\necho "running"\n' > ~/myscript.sh
$ stat -c '%n : %x' ~/myscript.sh 
/home/terdon/myscript.sh : 2016-02-23 10:36:49.349656971 +0200

$ chmod 700 ~/myscript.sh 
$ stat -c '%n : %x' ~/myscript.sh  ## This doesn't change atime
/home/terdon/myscript.sh : 2016-02-23 10:36:49.349656971 +0200

$ ~/myscript.sh 
running
$ stat -c '%n : %x' ~/myscript.sh   ## Running the script does
/home/terdon/myscript.sh : 2016-02-23 10:38:20.954893580 +0200
Run Code Online (Sandbox Code Playgroud)

但是,如果脚本驻留在使用noatimerelatime选项(或可能影响atime修改方式的任何其他可能选项)挂载的文件系统上,则行为将有所不同:

   noatime
          Do  not  update inode access times on this filesystem (e.g., for
          faster access on the news spool to speed up news servers).  This
          works  for all inode types (directories too), so implies nodira?
          time.

   relatime
          Update inode access times relative to  modify  or  change  time.
          Access time is only updated if the previous access time was ear?
          lier than the current modify or change time.  (Similar to  noat?
          ime,  but  it doesn't break mutt or other applications that need
          to know if a file has been read since the last time it was modi?
          fied.)

          Since Linux 2.6.30, the kernel defaults to the behavior provided
          by this option (unless noatime was specified), and the  stricta?
          time  option  is  required  to obtain traditional semantics.  In
          addition, since Linux 2.6.30, the file's  last  access  time  is
          always updated if it is more than 1 day old.
Run Code Online (Sandbox Code Playgroud)

您可以通过运行mount不带参数的命令来检查您安装的系统正在使用哪些选项。我上面显示的测试是在使用该relatime选项挂载的文件系统上运行的。使用此选项,atime如果 i) 当前atime比当前修改或更改时间早或 ii) 超过一天未更新,则更新。

因此,在具有 的系统上relatimeatime如果当前文件atime比当前修改时间新,则在访问文件时不会更改:

$ touch -ad "+2 days" file
$ stat --printf 'mtime: %y\natime: %x\n' file
mtime: 2016-02-23 11:01:53.312350725 +0200
atime: 2016-02-25 11:01:53.317432842 +0200
$ cat file 
$ stat --printf 'mtime: %y\natime: %x\n' file
mtime: 2016-02-23 11:01:53.312350725 +0200
atime: 2016-02-25 11:01:53.317432842 +0200
Run Code Online (Sandbox Code Playgroud)

atime如果超过一天,则总是在访问时更改。即使修改时间较旧:

$ touch -ad "-2 days" file
$ touch -md "-4 days" file
$ stat --printf 'mtime: %y\natime: %x\n' file
mtime: 2016-02-19 11:03:59.891993606 +0200
atime: 2016-02-21 11:03:37.259807129 +0200
$ cat file
$ stat --printf 'mtime: %y\natime: %x\n' file
mtime: 2016-02-19 11:03:59.891993606 +0200
atime: 2016-02-23 11:05:17.783535537 +0200
Run Code Online (Sandbox Code Playgroud)

因此,在大多数现代 Linux 系统上,atime除非文件自上次访问以来已被修改,否则只会每天更新一次。