在任何符合 POSIX 的 shell 中获取自纪元以来的秒数 [英] Get seconds since epoch in any POSIX compliant shell

查看:23
本文介绍了在任何符合 POSIX 的 shell 中获取自纪元以来的秒数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法在任何符合 POSIX 的 shell 中获取自 UNIX 时代以来的秒数,而无需求助于非 POSIX 语言(如 perl),或使用非 POSIX 扩展(如 GNU awk 的 strftime 函数).

I'd like to know if there's a way to get the number of seconds since the UNIX epoch in any POSIX compliant shell, without resorting to non-POSIX languages like perl, or using non-POSIX extensions like GNU awk's strftime function.

这里有一些我已经排除的解决方案......

Here are some solutions I've already ruled out...

date +%s//在 Solaris 上不起作用

date +%s // Doesn't work on Solaris

我看过一些 shell 脚本 之前建议,解析 date 的输出然后从格式化的公历日期派生秒,但他们不似乎没有考虑闰秒之类的细节.

I've seen some shell scripts suggested before, which parse the output of date then derive seconds from the formatted gregorian calendar date, but they don't seem to take details like leap seconds into account.

GNU awk 具有 strftime 功能,但这在标准 awk 中不可用.

GNU awk has the strftime function, but this isn't available in standard awk.

我可以编写一个调用 time 函数的小 C 程序,但二进制文件将特定于特定架构.

I could write a small C program which calls the time function, but the binary would be specific to a particular architecture.

是否有一种跨平台的方法可以仅使用符合 POSIX 的工具来做到这一点?

Is there a cross platform way to do this using only POSIX compliant tools?

我很想放弃并接受对 perl 的依赖,它至少已被广泛部署.

I'm tempted to give up and accept a dependency on perl, which is at least widely deployed.

perl -e 'print time'//作弊(非 POSIX),但应该适用于大多数平台

perl -e 'print time' // Cheating (non-POSIX), but should work on most platforms

推荐答案

这是一个可移植的/POSIX 解决方案:

Here is a portable / POSIX solution:

PATH=`getconf PATH` awk 'BEGIN{srand();print srand()}'

C 编译器或 Perl 不同,awk 保证出现在符合 POSIX 的环境中.

Unlike a C compiler or Perl, awk is guaranteed to be present on a POSIX compliant environment.

工作原理:

  • PATH=`getconf PATH` 正在确保 awkPOSIX 版本被调用它应该不是 PATH 中的第一个.

  • PATH=`getconf PATH` is making sure the POSIX version of awk is called should it not be the first one in the PATH.

根据 POSIX 标准 :srand([expr])将 rand 的种子值设置为 expr 或如果省略 expr 则使用一天中的时间.应返回先前的种子值.

Per the POSIX standard : srand([expr]) Set the seed value for rand to expr or use the time of day if expr is omitted. The previous seed value shall be returned.

第一次调用省略了一个参数,因此种子值设置为一天中的时间.第二个调用返回一天中的那个时间,这是自纪元以来的秒数.

The first call is omitting a parameter so the seed value is set to the time of day. The second call is returning that time of day, which is the number of seconds since the epoch.

请注意,对于许多 awk 实现而不是 GNU 实现(gawk),不需要第一次调用,因为该函数已经首先返回了预期值.

Note that with many awk implementations but not the GNU one (gawk), this first call is not required as the function already returns the expected value in the first place.

这篇关于在任何符合 POSIX 的 shell 中获取自纪元以来的秒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆