-1

I hope you all are doing great. I am new to Linux shell scripting. I am trying to learn basic shell scripting and i started with with if else condition and I am stuck in it since a week. I have read as many articles as I could but I am not understanding what is the problem here. I know this must a very basic for you guys but please help me :)

Here is the script that I wrote

#!/bin/sh

count=102

if [$count -gt 100]

then

echo "$count is greater than 100"

else

echo "$count is less than 100"

fi

When I execute this script, I am getting below error.

./count.sh: line 5: [102: command not found
102 is less than 100

*I also tried taking user input not just with integer but with string also, still getting the same error. please help :)

Thank you in advance

tripleee
  • 139,311
  • 24
  • 207
  • 268

1 Answers1

2

you need to provide space after [ and before ]. For e.g

[ $count -gt 100 ]

Sample code :

count=102
if [ $count -gt 100 ]
then
echo "$count is greater than 100"
else
echo "$count is less than 100"
fi
Achal
  • 11,629
  • 2
  • 14
  • 34
  • Specifically, this is because `[` is a command, but if you do `[$count` without a space, it tries to run the command `[102` instead, which is not a valid command. – Daniel H Dec 31 '18 at 05:09
  • True @DanielH agree. – Achal Dec 31 '18 at 05:10
  • See the "Answer Well-Asked Questions" section of [How to Answer](https://stackoverflow.com/help/how-to-answer), particularly the bullet regarding questions which "have already been asked and answered many times before". – Charles Duffy Dec 31 '18 at 05:10
  • @CharlesDuffy Got the point. Thanks for pointing that. – Achal Dec 31 '18 at 05:21
  • Hey @DanielH I tried your suggestion and it worked. Thank you so much for the help :) God bless you! – Rekha Mishra Dec 31 '18 at 05:22
  • BTW, you'd get more reliable error messages if quoting the expansion: `[ "$count" -gt 100 ]` will expand to `[ '' -gt 100 ]` if the variable is empty, which gives a (more useful) error about the empty string not being an integer, whereas `[ $count -gt 100 ]` will expand to `[ -gt 100 ]`, which gives a less-helpful error about `-gt` not being a unary operator. – Charles Duffy Dec 31 '18 at 14:34