0

I am trying to write a script then search for all the directories with the given substring but I am getting the following error.

I have no idea why this is happening.. can someone please guide me ?

#!/bin/bash
echo $1

for recordings in $1/*/ ; do
    echo $recordings | grep -q "XavierA"
    echo $?
    if ["$?" -eq 0];then
            echo "found."
    fi
done

The output is this

0
./readallfiles.sh: line 7: [0: command not found
1
./readallfiles.sh: line 7: [0: command not found
0
./readallfiles.sh: line 7: [0: command not found
1
./readallfiles.sh: line 7: [0: command not found
0
./readallfiles.sh: line 7: [0: command not found
1
./readallfiles.sh: line 7: [0: command not found
0
./readallfiles.sh: line 7: [0: command not found
1
./readallfiles.sh: line 7: [0: command not found
0
./readallfiles.sh: line 7: [0: command not found
1
./readallfiles.sh: line 7: [0: command not found
0
./readallfiles.sh: line 7: [0: command not found
1
./readallfiles.sh: line 7: [0: command not found
0
./readallfiles.sh: line 7: [0: command not found
1
./readallfiles.sh: line 7: [0: command not found
0
./readallfiles.sh: line 7: [0: command not found
1
./readallfiles.sh: line 7: [0: command not found
0
./readallfiles.sh: line 7: [0: command not found
1
./readallfiles.sh: line 7: [0: command not found
0
./readallfiles.sh: line 7: [0: command not found
1
./readallfiles.sh: line 7: [0: command not found

  • Note that running your code through http://shellcheck.net/ will identify this and other bugs automatically. `$1/*/` should be `"$1"/*/` to work right with directory names with spaces and glob characters; and the remaining lines would be better written as `if [[ $recordings = *XavierA* ]]; then echo "found"; fi` -- though you also just have your whole glob search for `"$1"/*XavierA*/` and avoid the need for a loop altogether. See [BashFAQ #4](http://mywiki.wooledge.org/BashFAQ/004) re: best practices for counting how many directory entries match a pattern. – Charles Duffy Mar 24 '20 at 17:17

1 Answers1

1

"[" isn't a punctuation mark, it's a program. Put a space after it, and before the "]".

The error message shows the shell has expanded the "$?" to 0, but it's adjacent to the [ so the shell is looking for an executable "[0". Naturally, it doesn't find one.

mpez0
  • 2,815
  • 17
  • 12
  • In [How to Answer](https://stackoverflow.com/help/how-to-answer), see the section "Answer Well-Asked Questions", and therein the bullet point regarding questions that have "been asked and answered many times before". – Charles Duffy Mar 24 '20 at 17:15