0

I have a bash script that will print yesterdays date. It looks like this:

#!/bin/bash

YESTERDAY_DATE=$(date '+%Y-%m-%d' -d '1 day ago')
echo $YESTERDAY_DATE

and I can run it like: ./script.sh, output as follows:

2021-02-23

Now, I want to be able to override it at execution time so I went ahead and changed it to:

#!/bin/bash

: ${YESTERDAY_DATE=$(date '+%Y-%m-%d' -d '1 day ago')}
YESTERDAY_DATE_OVERRIDE=${$YESTERDAY_DATE:-(date '+%Y-%m-%d' -d '1 day ago')}
echo $YESTERDAY_DATE

and when I run it like: YESTERDAY_DATE=2015-12-30 ./script.sh, output as follows:

./script.sh: line 4: ${$YESTERDAY_DATE:-(date '+%Y-%m-%d' -d '1 day ago')}: bad substitution
2015-12-30

It does print the overridden date but with a bad substitution error. Is there a better way to do this?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Saffik
  • 911
  • 4
  • 19
  • 45
  • 1
    Drop the `$` before `YESTERDAY_DATE:-`. – M. Nejat Aydin Feb 24 '21 at 17:29
  • 1
    ... and replace `:-` with `:=$`. – Cyrus Feb 24 '21 at 17:32
  • Thanks. Do you wanna put that as an answer so I can mark it as resolved? – Saffik Feb 24 '21 at 17:34
  • 1
    I propose to close the question with reference to [Assigning default values to shell variables with a single command in bash](https://stackoverflow.com/q/2013547/3776858) – Cyrus Feb 24 '21 at 17:38
  • More details: [Parameter Expansion](https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion) – Cyrus Feb 24 '21 at 17:39
  • 1
    Does this answer your question? [Assigning default values to shell variables with a single command in bash](https://stackoverflow.com/questions/2013547/assigning-default-values-to-shell-variables-with-a-single-command-in-bash) – Shane Bishop Feb 24 '21 at 17:47
  • 1
    I agree that the duplicate is helpful (which is why I helped close the question as a duplicate). However, the primary problem in the code shown is a missing `$` in `YESTERDAY_DATE_OVERRIDE=${$YESTERDAY_DATE:-(date '+%Y-%m-%d' -d '1 day ago')}`, which should have a `$` before the open parenthesis: `YESTERDAY_DATE_OVERRIDE=${$YESTERDAY_DATE:-$(date '+%Y-%m-%d' -d '1 day ago')}` so that the parenthesized expression is evaluated as a command substitution. – Jonathan Leffler Feb 24 '21 at 17:59

0 Answers0