[mdlug] Extracting the day of the Week in BASH
Daniel Hedlund
daniel at digitree.org
Sat Mar 10 00:14:10 EST 2007
Ingles, Raymond wrote:
>> From: Robert Adkins
>
>> Anyone know either the variable that returns the actual day of the
>> week or a very short script to extract the day of the week?
>
> date | cut -d" " -f 1
Be careful about using "date" this way (or with +%a or +%A) to extract
the day of the week if you're going to compare it against something. I
believe just running "date" will grab the date based on the current
locale. If your script might get run in an environment where the locale
is set to another language, you could get something unexpected. For
example, if you're doing any comparisons in your script such as to only
do something on Tuesday, you might write:
if [ "$(date +%A)" = "Tuesday" ]; then
echo "today is Tuesday..."
fi
This could cause a problem if the locale returns the day of the week in
a slightly different format. In this circumstance, you would probably
want to use +%u for extracting the day of the week as a number. I
believe this option is hard-coded to start on Monday irrespective of locale:
if [ $(date +%u) -eq 2 ]; then
echo "today is Tuesday...";
fi
Let me know if I'm mistaken.
Cheers,
Daniel Hedlund
daniel at digitree.org
More information about the mdlug
mailing list