Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the last Saturday of the month in a bash script

Tags:

bash

shell

I'm making a backup script in which I need to find the last Saturday of each month.

I've tried different approaches to finding the day itself, which works splendidly themselves.

The problem is, when I try putting them into my script I always get the error code ./test.sh: line 13: [: 29: integer expression expected.

This is my code:

#!/bin/bash

LASTSAT=$(ncal | grep Sa | awk '{print$(NF-0)}')
SATURDAY="6"

DAY=$(date +"%u")
DATE=$(date +"%d")

echo "$DAY"
echo "$DATE"
echo "$LASTSAT"

if [ $DATE -eq $LASTSAT  ]
then
 echo "sista lördagen..."
fi

I got the tip to change the if statements to [ "$DATE" = "$LASTSAT" ] which erased the error itself, but the script will somehow not equal 27 to 27 (to take this month as an example).

I also tried another approach to finding the last Saturday which was LASTSAT=$(cal|awk '{if(NF==7){SAT=$7}};END{print SAT}'), but it returns the exact same error if I use -eq and doesn't equal 27 to 27 using " with =

I'm very confused and out of ideas and I have searched the internet and copied the exact lines others been using but it all ends up the same.

What am I doing wrong?

like image 616
Jompa Avatar asked Nov 27 '25 14:11

Jompa


1 Answers

During testing I changed the target day and some of the variable names, but the following script works, for the next-to-last Sunday of the month. The critical change, relative to your script, was adding the -h switch to ncal, to turn off highlighting of the current day. The highlighting characters apparently come through when awk prints the field, but aren't visible when you do the echos. Note, you can drop the grep after ncal via an awk match.

#!/bin/bash

DoDay=$(ncal -h |awk '/Su/ {print $(NF-1)}')
Datum=$(date +%d)
echo $Datum Datum
echo $DoDay DoDay

if [[ $Datum == $DoDay ]]
then
    echo "sista lördagen..."
else
    echo "doh"
fi
like image 198
James Waldby - jwpat7 Avatar answered Nov 29 '25 09:11

James Waldby - jwpat7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!