Shell Value substitution in date(1) command

Hello Shell Experts,

I need date(1) output like this:

YESTERDAY=`date -v -1d "+%Y%m%d"`

Is there a way to substitute date -v -1d with date -v -$other_dayd?
 
Code:
$ echo $SHELL
/bin/sh
$ YESTERDAY=`date -v -1d "+%Y%m%d"`
$ echo $YESTERDAY
20170201
$ other_dayd="2d"
$ OTHERDAY=`date -v -$other_dayd "+%Y%m%d"`
$ echo $OTHERDAY
20170131
 
Thank you leebrown66. That was too easy :)

This is what I tried:

$ other_day=2
$ OTHERDAY=`date -v -$other_dayd "+%Y%m%d"`
-: Cannot apply date adjustment
usage: date [-jnRu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ...
[-f fmt date | [[[[[cc]yy]mm]dd]HH]MM[.ss]] [+format]


In your example though how does date(1) "figure out" that the value of $other_dayd should be interpreted as "d" for "day"?

Thank you too, tobik and Kernan.
 
In your example though how does date(1) "figure out" that the value of $other_dayd should be interpreted as "d" for "day"?
In his example the variable other_dayd contains 2d, so the argument becomes -2d when the variable is expanded, and is interpreted by the date command as normal.

The problem with your example above is that the shell is looking for a variable called $other_dayd, which doesn't exist. It has no way of knowing that the variable is actually $other_day, and that the d is just plain text that should be left as is. As tobik mentioned, you can wrap the variable name in curly brackets to let the shell interpreter know that the d is not part of the variable name.
 
My mistake for not realizing the trailing d was not part of the variable name. So, reworked, with an additional example and apologies for any confusion :

Code:
$ echo $SHELL
/bin/sh
$ YESTERDAY=`date -v -1d "+%Y%m%d"`
$ echo $YESTERDAY
20170209
$ other_day="2"
$ OTHERDAY=`date -v -${other_day}d "+%Y%m%d"`
$ echo $OTHERDAY
20170208
sign taken into variable instead
Code:
$ other_day="-3"
$ OTHERDAY=`date -v ${other_day}d "+%Y%m%d"`
$ echo $OTHERDAY
20170207
 
Back
Top