0

I trying to find out a weekday from last month dates in a loop but have an error

'past_month_date: command not found'

The $past_month_date was calculated right and has format 20200131 But if I'm using date then it works.

weekday=$(date +%a)

here is my shell script:

#!/bin/bash

day_num=$(date +%u)
date=$(date +%Y%m%d)
month=$(date +%m)
year=$(date +%Y)

if [ $day_num -eq 1 ]
then
    for (( h = 2; h <= 31; h ++))
    do
        past_month_date=$(date -d "-1 month" +%Y%m$h)
        echo $past_month_date
        weekday=$(past_month_date +%a)
        echo $weekday
        #if [ $weekday -ne $sunday ]
        #then
            #....
        #fi
    done
fi
LDropl
  • 846
  • 3
  • 9
  • 25

2 Answers2

1

I think the problem is the difference between date and past_month_date. Using date in your script works because date is a command that returns a date/time (by default it is the current date/time) and uses various arguments, such as +%a to format it differently.

In your script past_month_date is a variable that is being used to store the value returned from the date command for a date one month ago, formatted in a particular way. The variable is not able to change the format just by being passed a parameter like "+%a", so you will probably need to use another command to convert that date into the format that you want. Luckily, there is a command that does exactly that: date. (As I was reminded by this SO question ).

If you call date and pass it a parameter of "--date=${past_month_date}" as well as any formatting that you need (such as "+%a"), then I think you will find that it does the job. So your "weekday=" line would read:

weekday=$(date --date=${past_month_date} +%a)

I've just made a copy of your example script and made this change and it seemed to work for me :)

mdmay74
  • 70
  • 1
  • 7
1

your weekday variable should be as below :

weekday=$(date --date $past_month_date +%a)
nullPointer
  • 4,419
  • 1
  • 15
  • 27