Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Problem: I need to check if today is Thursday and perform different actions based on the result of this condition. I tried two different approaches:

Getting the Day Name:

DAYOFWEEK=$(date +"%a")
echo DAYOFWEEK: $DAYOFWEEK
if ["$DAYOFWEEK" == "Thu"]; 
then   
   echo YES
else
    echo NO
fi

Getting the Day Num:

DAYOFWEEK=$(date +"%u")
echo DAYOFWEEK: $DAYOFWEEK

if ["$DAYOFWEEK" == 4]; 
then
   echo YES
else
   echo NO
fi

In both cases, the output is NO, even though it should be YES. What is wrong?

share|improve this question
    
Perfect, Thanks a log. –  Swagatika Mar 7 '13 at 12:36
1  
A side note: those ; would be required if you would have then in the same line with if. In this case they are redundant. –  manatwork Mar 7 '13 at 12:40

2 Answers 2

up vote 7 down vote accepted

The problem is the missing blank.

The following code will work:

if [ "$DAYOFWEEK" == 4 ];  then    echo YES; else    echo NO; fi

But keep in mind (see help test):

  • == is not officially mentioned, you should use = for string compare
  • -eq is intended for arithmetic tests

I would prefer:

 if [ "${DAYOFWEEK}" -eq 4 ];  then    echo YES; else    echo NO; fi

Generally you should prefer the day number approach, because it has less dependency to the current locale. On my system the output of date +"%a" is today Do.

share|improve this answer

Firstly you should quote the assignment DAYOFWEEK="$(date +%u)"

And you need to have spaces on each side of the [ and ] brackets.

The semi-colon at the end of the line is redundant.

share|improve this answer
1  
The quoting is not needed. –  H.-Dirk Schmitt Mar 7 '13 at 14:51
    
To expand on @H.-DirkSchmitt's comment: the reason why the quoting is not needed is that the output will not contain any spaces. –  Michael Kjörling Mar 7 '13 at 15:07
    
@MichaelKjörling: No - it is never needed ;-) Try the example: a=$(echo 1 2 3); echo $a; –  H.-Dirk Schmitt Mar 7 '13 at 15:45
    
@H.-DirkSchmitt a=$(echo "1 2 3"); echo $a with multiple spaces between the digits (StackExchange won't let me make it a simple copy-and-paste, unfortunately). –  Michael Kjörling Mar 7 '13 at 15:54
    
@MichaelKjörling - see man bash "If the substitution appears within double quotes, word splitting and pathname expansion are not performed on the results." So it makes in the case of the question and the "1 2 3" example no difference. –  H.-Dirk Schmitt Mar 7 '13 at 16:03

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.