0

I just wanted to count the occurrence of a particular string. This is my code:

count=0
output="hai how are you ? my-code is incorrect. Do you have a new my-code ?"
echo $output

for word in $output
do
    if ["$word" == "my-code"];then
        count=$((count + 1))
    fi
done

echo $count

Sadly, this is my output :

hai how are you ? my-code is incorrect. Do you have a new my-code ?
./test.sh: line 7: [hai: command not found
./test.sh: line 7: [how: command not found
./test.sh: line 7: [are: command not found
./test.sh: line 7: [you: command not found
./test.sh: line 7: [?: command not found
./test.sh: line 7: [my-code: command not found
./test.sh: line 7: [is: command not found
./test.sh: line 7: [incorrect.: command not found
./test.sh: line 7: [Do: command not found
./test.sh: line 7: [you: command not found
./test.sh: line 7: [have: command not found
./test.sh: line 7: [a: command not found
./test.sh: line 7: [new: command not found
./test.sh: line 7: [my-code: command not found
./test.sh: line 7: [?: command not found
0

I am getting error at the string comparison step. I just searched and came across this. I believe I have done the same. What's the bug here?

Community
  • 1
  • 1
0aslam0
  • 1,607
  • 5
  • 23
  • 40

2 Answers2

1

[ is an ordinary shell command. Like all commands, you need to put a space between the command name and the arguments:

if [ "$word" == my-code ]; then

It also requires that ] be a separate argument so that it will ignore it at the end.

Barmar
  • 669,327
  • 51
  • 454
  • 560
1

Your have many syntax errors like spaces after [ and before ] and around == etc..

However you can avoid a loop by using tr to get your job done:

tr ' ' '\n' <<< "$output" | grep -c 'my-code'
2
anubhava
  • 713,503
  • 59
  • 514
  • 593