Bash: How to Check if Date is a Weekend


Often you may want to use Bash to check if a particular date is on a weekend.

You can use the following syntax to do so:

if [[ $(date +%u) -gt 5 ]]; then
  echo "Date is on a weekend"
else
  echo "Date is not on a weekend"
fi

This particular example checks if the current date is on a weekend and outputs one of the following as a result:

  • Date is on a weekend
  • Date is not on a weekend

This syntax works by using date +%u to return the current date as a day of the week where:

  • Monday = 1
  • Tuesday = 2
  • Wednesday = 3
  • Thursday = 4
  • Friday = 5
  • Saturday = 6
  • Sunday = 7

By using an if statement, we’re able to check if the resulting number is greater than 5.

If the number is greater than 5 then we know the current date is equal to either 6 or 7, which are weekends.

Otherwise, we know that the current date is 5 or less, which represents weekdays.

The following example shows how to use this syntax in practice.

Example: How to Check if Date is on a Weekend

We can use the date command in Bash to display the current date:

We can see that the current date is Friday, August 23, 2024.

We can use the following syntax to check if today is a weekend or not:

if [[ $(date +%u) -gt 5 ]]; then
  echo "Date is on a weekend"
else
  echo "Date is not on a weekend"
fi

The following screenshot shows how to use this syntax in practice:

Bash check if date is on a weekend

The output returns “Date is not on a weekend” because today (Friday) it is not currently a weekend.

To display the day of the week for the current day, we can use the following syntax:

date +%A

The following screenshot shows how to use this syntax in practice:

Notice that this returns Friday, which represents the current day of the week.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Get Day of Week
Bash: How to Get Month Name
Bash: How to Compare Dates
Bash: How to Extract Date from String

Leave a Reply