1

I'm very new to UNIX coding so please be kind. I am trying to use the date command to obtain the current month's abbreviated name and store it into a variable. I'm using this variable to check against in an if statement to see if it is equal to "Jan" which it should be. I even echo the variable first to test the value and it prints Jan. Unfortunately, the if statement refuses to catch the variable being equal to "Jan" even though it seems as though it is. I have tried using the cut command to select the first 3 characters only to help rule out any trailing white spaces or other format issues. Any ideas why the date function is just not working as expected?

Here is my script:

#! /bin/bash

month= date +"%b"

if[[ $month == "Jan"]]
then
echo The current month, January has 31 days

else
echo Error retrieving month!
fi

I am running it from the terminal on a Ubuntu virtual machine as a bash script.

  • Paste your code to http://shellcheck.net/ - it will point out the syntax errors. – tripleee Jan 21 '16 at 05:14
  • 1
    Don't take the downvote personally; it's a help for future visitors more than actionable feedback for you (though please do feel welcome to review the [help] and the [`bash` tag wiki](http://stackoverflow.com/tags/bash/info) before posting your next question). – tripleee Jan 21 '16 at 05:17
  • Oh, http://shellcheck.net/ misses the error in the `date` assignment because what you have is syntactically valid, it just doesn't do what you want it to. See [this](http://stackoverflow.com/questions/2268104/bash-script-variable-declaration-command-not-found) and [this](http://stackoverflow.com/questions/4651437/how-to-set-a-variable-equal-to-the-output-from-a-command-in-bash). – tripleee Jan 21 '16 at 05:23
  • I'll have to remember that site for checking syntax, thanks. – SpecterCody Jan 21 '16 at 07:09

1 Answers1

1

bash can be finicky about the if syntax (e.g. spaces matter). Also, you needed virgule [or equivalent] syntax:

#! /bin/bash

month=`date +"%b"`

if [[ "$month" == "Jan" ]] ; then
    echo The current month, January has 31 days
else
    echo Error retrieving month!
fi
Craig Estey
  • 30,627
  • 4
  • 24
  • 48
  • *Edit - used ' instead of `, oops! Got it working! Thanks very much for your help! – SpecterCody Jan 21 '16 at 05:39
  • You're welcome! We were [both] lucky. I was able to post the answer just before tripleee closed the question. It saved me the trouble of reopening, just to post ;-). IMO, your question was well presented, etc. – Craig Estey Jan 21 '16 at 05:48