Issue
I would like to pass Dates
into command line as well as Shell script.
For eg. the script is called MoneyCalculator.sh, and I would like to calculate the past 10 dates and pass the parameters into the script on command line.
./MoneyCalculator.sh date +"%Y-%m-%d" -d "-10 days" date +"%Y-%m-%d" -d "-1 days"
The above didn't work, I tried to use [] but still didn't work. Any one knows how I should pass it?
In addition, in shell script, if I would like to use as a variable;
moneyDate=date +"%Y-%m-%d" -d "-10 days" <<< this doesnt work either.
Solution
It's not completely clear to me what you're looking to do here, but maybe this helps anyway?
I'm going to suppose you want to pass two arguments to the ./MoneyCalculator.sh
script, where the first one is 10 days prior to today and the second one is the day before today (i.e., yesterday). In this case I think I would suggest:
./MoneyCalculator.sh `date -I -v -10d` `date -I -v -1d`
If that's not exactly what you have in mind (and I doubt it is), I am optimistic that you will be able to adapt the approach to your specific needs.
I created a simple script that simply does echo $1 $2
and found that today, it printed 2023-04-23 2023-05-02
so that works as I expected. Good luck!
EDIT 1:
@Bodo points out that a new syntax $(...)
is preferred over backticks and I'll use that in the following example, showing defining/using variables and turning your parameter into a date instance within the script...
#!/bin/bash
D1=$1 # defines D1 as your first date
D2=$2 # defines D2 as your second date
echo $(date -I -j -v -1y -f "%Y-%m-%d" $D1) # specify a date (D1) then subtract one year
echo $D1 $D2
Remember to make your script executable with chmod +x
, of course. Enjoy!
Answered By - unigeek Answer Checked By - Clifford M. (WPSolving Volunteer)