Get Day Of Week in bash script
BashSedBash 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
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