Issue
Can someone tell me what I'm doing wrong, please?
I've got this block of code
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;
that should output the expiration time of my MFA token, but I get this error
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]
I'm on a Macbook and I suspect it's something to do with the date format. I'm just not sure what it is.
Solution
The default date format for BSD date
is [[[mm]dd]HH]MM[[cc]yy][.ss]]
. If MFS_Exp
is in that format, you can use
exp_sec=$(( $(date -j "$MFS_Exp" +%s) - $(date +%s) ))
If not, you need to specify the input format using the -f
option. For example, if your string is like 2020-12-18 12:34:56
, then use date -j -f '%Y-%m-%d %H:%M:%S' "$MFS_Exp" +%s
.
For the second call, I wouldn't recommend using date
at all, as you are working with a duration, not a timestamp.
hours=$(( exp_sec / 3600 ))
rem=$(( exp_sec % 3600 ))
minutes=$(( rem / 60 ))
sec=$(( rem % 60 ))
output+=", MFA TTL: ${hours}h ${minutes}m ${sec}s"
Answered By - chepner Answer Checked By - Dawn Plyler (WPSolving Volunteer)