[mdlug] Extracting the day of the Week in BASH

Robert Adkins radkins at impelind.com
Sat Mar 10 06:02:44 EST 2007



Daniel Hedlund wrote:
> 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
>   
    Thanks for your concern.

    This script is special purpose for one environment. In order to use 
it in another environment, I would have to edit it, at least slightly. 
Which is why I am fully commenting the script as I create/build it.

    Rob



More information about the mdlug mailing list