Why is my bash script showing [2: command not found?

40 views Asked by At

So here is my small bash script:

#!/bin/sh
echo "arg 0=" $0
echo "arg 1=" $1
echo "arg 2=" $2

if [$# -eq 1]; then
  cal $1
elif [$# -eq 2]; then
  cal $1 $2
else
  echo Incorrect amount of arguments used
fi

Once I start by executing the script using

./calscript.sh 5 2020

Then I get the following error

arg 0= calscript.sh
arg 1= 5
arg 2= 2020
calscript.sh: line 6: [2: not found
calscript.sh: line 8: [2: not found
Incorrect amount of arguments used

Can anyone tell me what I am doing wrong?

I was expecting to be shown the calendar tools may 2020 on the terminal.

1

There are 1 answers

1
Ömer Sezer On BEST ANSWER

Please use quote ("") around the variables and space after '[', ']'.

Code:

#!/bin/sh
echo "arg 0=" $0
echo "arg 1=" $1
echo "arg 2=" $2

if [ "$#" -eq 1 ]; then
  cal "$1"
elif [ "$#" -eq 2 ]; then
  cal "$1" "$2"
else
  echo "Incorrect amount of arguments used"
fi

Output:

Command => $ ./test.sh 5 2020
arg 0= ./test.sh
arg 1= 5
arg 2= 2020
      May 2020
Su Mo Tu We Th Fr Sa
                1  2
 3  4  5  6  7  8  9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31