I need to receive a code in bash, which will give me current date in this format:
Sunday, 1^st January 2016
(with superscript st
, nd
, rd
or th
) in 4 cases.
What is the way to receive superscript?
I would be thankful for any help.
I need to receive a code in bash, which will give me current date in this format:
Sunday, 1^st January 2016
(with superscript st
, nd
, rd
or th
) in 4 cases.
What is the way to receive superscript?
I would be thankful for any help.
The date
program doesn't have any conversions that produce ordinal numbers, so you'll need to substitute the suffix outside of it:
#!/bin/bash
d=$(date +%e)
case $d in
1?) d=${d}th ;;
*1) d=${d}st ;;
*2) d=${d}nd ;;
*3) d=${d}rd ;;
*) d=${d}th ;;
esac
date "+%A, $d %B %Y"
Note that most English style guides recommend against writing the ordinal suffix as a superscript; if you really insist on it, you can treat that as an exercise!
Note also, that by invoking date
twice, we risk a race condition at midnight. We can avoid this by separately finding the current time and then formatting it:
#!/bin/bash
s=$(date +@%s)
d=$(date -d $s +%e)
case $d in
1?) d=${d}th ;;
*1) d=${d}st ;;
*2) d=${d}nd ;;
*3) d=${d}rd ;;
*) d=${d}th ;;
esac
date -d $s "+%A, $d %B %Y"
Alternatively, read the date (once) into separate variables, and then format them in shell:
#!/bin/bash
IFS=_ read a d b y < <(date +%A_%e_%B_%Y)
case $d in
1?) d=${d}th ;;
*1) d=${d}st ;;
*2) d=${d}nd ;;
*3) d=${d}rd ;;
*) d=${d}th ;;
esac
echo "$a, $d $b $y"
I hope this helps:
#!/bin/bash
# get the day of the month to decide which postfix should be used
dayOfMonth=$(date +%d)
# Choose postfix
case "$dayOfMonth" in
1)
postfix="st"
;;
2)
postfix="nd"
;;
3)
postfix="rd"
;;
*)
postfix="th"
;;
esac
# Generate date string
myDate=$(date +%A,\%d\^$postfix\ %B\ %Y)
echo $myDate
Explanation:
Mind the comments.
The date command output can be formatted from the command line with a string starting with a "+", containing varius format options like %d for day of the month.
Type this into your terminal:
man date
to get the manual and check the FORMAT section.
Or if you want to run your app at very midnight as Toby Speight warned about it. Call date only once:
#!/bin/bash
# Generate date template
dateTpl=$(date +%A,\ \%d\^postfix\ %B\ %Y)
# get the day of the month from the template, to decide which postfix should be use
dayOfMonth=$(echo $dateTpl | cut -d ' ' -f 2 | sed 's/\^postfix//g' )
# Choose postfix
case "$dayOfMonth" in
1)
postfix="st"
;;
2)
postfix="nd"
;;
3)
postfix="rd"
;;
*)
postfix="th"
;;
esac
# Generate date string from template
myDate=$(echo $dateTpl | sed "s/postfix/$postfix/g")
echo $myDate