Search code examples
bashdatedirectorymkdir

Bash Script conditional statement for directory creation - command not found error


#!/bin/bash

dd=`date +%d`
mm=`date +%m`
yy=`date +%Y`
TODAY=`date +%d`
MONTH=`date +%m`
TOMORROW=`date +%d --date="1 days"`

echo $TODAY
echo $MONTH
#echo $TOMORROW


#if [ $TOMORROW < $TODAY ]; then
#   exit 0
#fi

cd /Users/name/monthly

if [$TODAY == 01 && $MONTH == 01];
then
    mkdir -p January
elif [$TODAY == 01 && $MONTH == 02];
then
    mkdir -p February
elif [$TODAY == 01 && $MONTH == 03];
then
    mkdir -p March
elif [$TODAY == 01 && $MONTH == 04];
then
    mkdir -p April
elif [$TODAY == 01 && $MONTH == 05];
then
    mkdir -p May
elif [$TODAY == 01 && $MONTH == 06];
then
   mkdir -p June
elif [$TODAY == 01 && $MONTH == 07];
then
    mkdir -p July
elif [$TODAY == 01 && $MONTH == 08];
then
    mkdir -p August
elif [$TODAY == 01 && $MONTH == 09];
then
    mkdir -p September
elif [$TODAY == 01 && $MONTH == 10];
then
    mkdir -p October
elif [$TODAY == 25 && $MONTH == 11];
then
    mkdir -p November
elif [$TODAY == 01 && $MONTH == 12];
then
    mkdir -p December
fi

I am trying to create the Directory for the every Month of using shell script. For the testing purpose, I use date 25 for November but the conditional statement will check if the date is 01 and month is 01..12 then it will create the folder accordingly.

Today and Month is printed but for the conditional statement, I got command not found the error.

test.sh: line 21: command not found .....


Solution

  • You would have seen your mistake immediately, if you would not just have looked at command not found, but what bash printed before that: It outputs the command which was not found.

    A conditional statement in bash has the form

    if COMMAND
    then 
       ....
    

    In your case, COMMAND is something like

    [$TODAY == 01 && $MONTH == 02]
    

    which is actually two commands, connected by &&. Let's assume that TODAY holds the string 05. In this case, you would have the command

    [05 == 01
    

    which means: Call a program stored in the file named [05, with the parameters == and 01. Since there likely is no file of this odd name in your PATH, you get command not found.

    There are several ways to solve this, but IMO, the most readable is

    if [[ $TODAY == 01 && $MONTH == 05 ]]
    

    In this case, we have [[ as command (and not [05), and since this is a syntactic element of bash instead of an external command, it does not terminate by the &&, but stretches up to the closing ]].