Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

BASH If Command Not Found

I have a slight problem with my BASH script that I do not know the cause.

Please take a look at this simple script.

#!/bin/bash
# Given two integers X and Y. find their sum, difference, product, and quotient

# Constraints
# -100 <= X,Y <= 100
# Y != 0

# Output format 
# Four lines containing the sum (X+Y), difference (X-Y), product (X x Y), and the quotient (X // Y) respectively.
# (While computing the quotient print only the integer part)

# Read data
echo "Please input for x and y!"
read x
read y

declare -i MIN=-100
declare -i MAX=100


# Checks if the valued read is in the constraints
if [ $x -gt $MAX ] || [ $x -lt $MIN ];
then
    echo "Error!"
    exit 1;
elif [ $y -gt $MAX ] || [$y -lt $MIN ] || [$y -eq 0];
then
    echo "Error"
    exit 1;
else
    for operator in {"+","-","*","/",}; do echo "$x $operator $y" | bc; done
fi

The output of the script above is as follow.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please input for x and y!
1
2
worldOfNumbers.sh: line 26: [2: command not found
worldOfNumbers.sh: line 26: [2: command not found
3
-1
2
0

As you can see, there is this [2: command not found. I believe there is something wrong with my syntax however I feel like I have typed the right one.

p.s. I use Oh My ZSH to run the program. I’ve also tried running in VS Code however the same thing arise.

Thank you for the help.

>Solution :

If you put your code through shellcheck, you’ll see that it is due to the lack of spaces between your variable and your bracket. Bash is a space oriented language, and [ and ] are commands just like echo or printf.

Change

elif [ $y -gt $MAX ] || [$y -lt $MIN ] || [$y -eq 0];

to

elif [ $y -gt $MAX ] || [ $y -lt $MIN ] || [ $y -eq 0 ];
                         ^                  ^        ^

Arrows added to show where spaces were added.

You can see that [ is a command if you run this at your bash prompt:

$ which [
[: shell built-in command

Because you do not have a space between [ and 2, bash assumes that you are trying to run a command called [2 and that command does not exist, as seen by your error message.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading