日期:选项需要一个参数



有人能告诉我我做错了什么吗?

我有这个代码块

if [ -n "${MFA_Exp}" ]; then
exp_sec="$(expr '(' $(date -d "${MFA_Exp}" +%s) - $(date +%s) ')' )";
if [ "${exp_sec}" -gt 0 ]; then
output+=", MFA TTL: $(date -u -d @"${exp_sec}" +"%Hh %Mm %Ss")";
else
output+=", MFA DEAD!";
fi;

它应该输出我的MFA令牌的到期时间,但我得到了这个错误

date: option requires an argument -- d
usage: date [-jnRu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ...
[-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]

我在Macbook上,我怀疑这与日期格式有关。我只是不确定是什么。

BSDdate的默认日期格式是[[[mm]dd]HH]MM[[cc]yy][.ss]]。如果MFS_Exp是这种格式,您可以使用
exp_sec=$(( $(date -j "$MFS_Exp" +%s) - $(date +%s) ))

如果没有,则需要使用-f选项指定输入格式。例如,如果字符串类似于2020-12-18 12:34:56,则使用date -j -f '%Y-%m-%d %H:%M:%S' "$MFS_Exp" +%s

对于第二个调用,我根本不建议使用date,因为您使用的是持续时间,而不是时间戳。

hours=$(( exp_sec / 3600 ))
rem=$(( exp_sec % 3600 ))
minutes=$(( rem / 60 ))
sec=$(( rem % 60 ))
output+=", MFA TTL: ${hours}h ${minutes}m ${sec}s"

最新更新