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

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

问题描述

我想知道是否有一种方法可以获取自任何POSIX兼容外壳中的UNIX纪元以来的秒数,而无需求助于诸如perl之类的非POSIX语言,或使用诸如GNU awk的strftime函数之类的非POSIX扩展名. .

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脚本

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.

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

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标准: 品牌([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天全站免登陆