There are a few problems I see.
- I don't recognize the
$[...]
syntax and can't find a shell that does (see the comments, below, where user @KamilCuk explains this further).
- The
if
syntax is wrong, possibly swapped with the previous line.
- Because of the parentheses, what's read as a less-than sign (
<
) is going to try to redirect input to a program.
- The answer will always print out.
- As you point out, there's no chance of a Julian day working with different years.
Try something like this, instead.
#!/bin/sh
Split up the dates for easier debugging, first, and also use `+%s to get "UNIX time" seconds since the start of 1970.
now=$(date +%s $now)
target=$(date +%s -d $1)
days=$(($target - $now));
Fix the conditional syntax.
if [ $days -lt 0 ]
then
echo error
exit 1
Put the output into an else
clause.
else
Since we have the answer in seconds, divide by the number of seconds in a typical day.
days=$(($days / 86400))
echo "There are $days days left to this date."
fi
I also cleaned up the echo
syntax for clarity.
Note that this still isn't perfect. Depending on your definition of "one day," there are going to be cases where the answer from this script differs from what you want; in that case, you'll need to adjust $target
to match a particular time of day. In addition, not every day is 86400 seconds long, because of daylight savings and leap seconds. But with those caveats, it should work well enough and adding those to a script sounds like more work than "how many days?" should warrant.
If you want to see the steps it takes for debugging, run it with sh -x date.sh '2022-12-31'
(with your script's name and date), since the -x
argument tells the shell to give you a "trace" of intermediate steps.