Home > Software design >  Bash shell: How to reformat string date from a variable value
Bash shell: How to reformat string date from a variable value

Time:12-07

I understand how to reformat a date using the date command, and I am fine with that. However, I have a wrinkle in that I am struggling with - the date I want to reformat is the output of another command, so I am storing it in the variable. I am struggling with the syntax of how to specify that I want to take the output of one command, and run it through date -d, and store it in another variable. Here is what I tried:

expdate=`get_expire_date.sh`
echo $expdate
Mon 23 Mar 2022 05:05:05 PM UTC
expdval=`date -d'($expdate)'`
echo $expdval

I get today's date, not the converted expire date from the script output. If I leave the parenthesis out, of course, it treats $expdate as the literal text to translate and gives an error, whereas if I leave the single quote marks off, it uses the spaces in the date string as a delimiter and only grabs the first token.

What am I doing wrong?

CodePudding user response:

I found I had to use double-quotes instead, like this (and sorry for the old way of doing things, updating to new shell syntax):

expdval=$(date -d"$(get_expire_date.sh)")

CodePudding user response:

First, parameter expansion doesn't occur inside single quotes. You would need to change the single quotes

expdval=`date -d'($expdate)'`

to double quotes

expdval=`date -d"($expdate)"`

Second, the parentheses create an invalid input, which results (for reasons I don't really understand) in an output of midnight of the current day. (You'll get the same result with the trivial invalid date date -d "".)

Drop the parentheses, and you'll get the same date back (because the input format matches the default output format).

$ date -d "$expdate"
Wed Mar 23 13:05:05 EDT 2022

To actually manipulate it, you'll need an explicit output format:

$ date -d "$expdate"  %Y-%m-%d
2022-03-23

or some form of date "arithmetic":

$ date -d "$expdate   2 days"
Fri Mar 25 13:05:05 EDT 2022
  • Related