如何在shell脚本中检测BSD与GNU版本的日期 [英] How can I detect BSD vs. GNU version of date in shell script

查看:189
本文介绍了如何在shell脚本中检测BSD与GNU版本的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个shell脚本,需要做一些日期字符串操作。该脚本应尽可能多地运行* nix变体,因此我需要处理机器可能具有BSD或GNU版本的日期的情况。



是测试操作系统类型的最优雅的方式,所以我可以发送正确的日期标记?



编辑:
To澄清,我的目标是使用在BSD和GNU中看起来不同的日期相对日期计算工具。



BSD示例

  date -v -1d 

GNU示例

  date --date =1天前


解决方案

使用便携式标志。该标准可用此处



对于打印相对日期的特殊问题,使用perl比日期更容易:

  perl -E'说标量本地时间(时间 -  86400)'

(注意这个解决方案完全失败23或25小时的时间,但是许多perl解决方案可以解决这个问题,请参见perl常见问题。)



但是你一定可以使用Keith的想法和做法:

 如果date -v 1d> / dev / null 2>& 1;那么
DATE ='date -v 1d'
else
DATE ='date --date =1天前'
fi
eval $ DATE

或只是

  DATE = $(date -v 1d> / dev / null 2>& 1)|| DATE = $(date --date =1天前)


I am writing a shell script that needs to do some date string manipulation. The script should work across as many *nix variants as possible, so I need to handle situations where the machine might have the BSD or the GNU version of date.

What would be the most elegant way to test for the OS type, so I can send the correct date flags?

EDIT: To clarify, my goal is to use date's relative date calculation tools which seem distinct in BSD and GNU.

BSD example

date -v -1d

GNU example

date --date="1 day ago"

解决方案

Use portable flags. The standard is available here

For the particular problem of printing a relative date, it is probably easier to use perl than date:

perl -E 'say scalar localtime( time - 86400 )'

(note that this solution utterly fails on 23 or 25 hour days, but many perl solutions are available to address that problem. See the perl faq.)

but you could certainly use a variation of Keith's idea and do:

if date -v 1d > /dev/null 2>&1; then
  DATE='date -v 1d'
else
  DATE='date --date="1 day ago"'
fi
eval $DATE

or just

DATE=$(date -v 1d > /dev/null 2>&1) || DATE=$(date --date="1 day ago")

这篇关于如何在shell脚本中检测BSD与GNU版本的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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