Get Day Of Week in bash script

BashSed

Bash Problem Overview


I want to have the day of week in the variable DOW.

So I use the following bash-script:

DOM=$(date +%d)
DOW=($($DOM % 7) ) | sed 's/^0*//'

Unfortunately there I get this error: bash: 09: command not found. The expected result is 2 ( 9 % 7 = 2) in the variable $DOW.

How can I get this working? It works for the days 1-8 but because of the C-hex, there is no number over 8 available and the following message appears: bash: 09: value too great for base (error token is "09").

Bash Solutions


Solution 1 - Bash

Use %u. Like this:

DOW=$(date +%u)

From the man page:

>%u day of week (1..7); 1 is Monday

Solution 2 - Bash

Using a different %-specifier is the real answer to your question. The way to prevent bash from choking on invalid octal numbers is to tell it that you actually have a base-10 number:

$ DOM=09
$ echo $(( DOM % 7 ))
bash: 09: value too great for base (error token is "09")
$ echo $(( 10#$DOM % 7 ))
2

Solution 3 - Bash

This works fine here

#!/bin/sh
DOW=$(date +"%a")
echo $DOW

Solution 4 - Bash

You can also use to return the day name

 date +'%A'

Solution 5 - Bash

You can use the - flag:

DOM=$(date +%-d)
             ^

which would prevent the day from being padded with 0.

From man date:

   -      (hyphen) do not pad the field

Observe the difference:

$ DOM=$(date +%d)
$ echo $((DOM % 7))
bash: 09: value too great for base (error token is "09")
$ DOM=$(date +%-d)
$ echo $((DOM % 7))
2

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbbholzbbView Question on Stackoverflow
Solution 1 - Bashhek2mglView Answer on Stackoverflow
Solution 2 - Bashglenn jackmanView Answer on Stackoverflow
Solution 3 - BashRonald HofmannView Answer on Stackoverflow
Solution 4 - BashAShahView Answer on Stackoverflow
Solution 5 - BashdevnullView Answer on Stackoverflow