Bash 日期/时间算法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/967780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 20:56:33  来源:igfitidea点击:

Bash date/time arithmetic

bashdatetimesleepsuspend

提问by Deniz Dogan

I have a little Bash script which suspends the computer after a given number of minutes. However, I'd like to extend it to tell me what the time will be when it will be suspended, so I can get a rough idea of how long time I have left so to speak.

我有一个小 Bash 脚本,它在给定的分钟数后挂起计算机。但是,我想延长它以告诉我暂停的时间是什么时候,这样我就可以大致了解我还剩下多长时间可以这么说。

#!/bin/sh
let SECS=*60
echo "Sleeping for"  "minutes, which is" $SECS "seconds."
sleep $SECS &&
pm-suspend

The only argument to the script will be how many minutes from now the computer should be suspended. All I want to add to this script is basically an echosaying e.g. "Sleeping until HH:nn:ss!". Any ideas?

脚本的唯一参数是从现在起计算机应该挂起的分钟数。我想添加到这个脚本的基本上是一个echo说法,例如“Sleeping until HH:nn:ss!”。有任何想法吗?

回答by Deniz Dogan

Found out how.

发现如何。

echo "The computer will be suspended at" $(date --date "now  minutes")

回答by Michiel Buddingh

On BSD-derived systems, you'd use

在 BSD 派生的系统上,你会使用

date -r $(( $(date "+%s") +  * 60 ))

i.e. get the current date in seconds, add the number of minutes, and feed it back to date.
Yeah, it's slightly less elegant.

即以秒为单位获取当前日期,添加分钟数,并将其反馈到日期。
是的,它稍微不那么优雅。

回答by Chris

on linux

在 linux 上

SECS=`date "+$s"`
SECS=$(( SECS +  * 60 ))
date --date $SECS