16

So I'm writing a bash shell script, and my first few lines looks like this:

if ! [ $# -eq 0 || $# -eq 1 ]; then
    echo -e "Usage: myScriptName [\e[3mdir\e[0m] [\e[3m-f file\e[0m]"
    exit 1
fi

But when I run it, it says "[: missing `]'". I don't see a missing ], and nothing except the ; is touching the ], so what am I missing?

Majora320
  • 1,321
  • 1
  • 13
  • 33
  • 3
    [ShellCheck](http://www.shellcheck.net/) might help. – kojiro Feb 09 '16 at 00:27
  • 1
    Since `||` separates two commands, `[` receives the value of `$#`, `-eq`, and `0` as its arguments. To maintain the illusion of being syntax, `[` requires a "matching" `]` as its final argument. – chepner Feb 09 '16 at 04:21

3 Answers3

27

You cannot use operators like || within single-brace test expressions. You must either do

! [[ $# -eq 0 || $# -eq 1 ]]

or

! { [ $# -eq 0 ] || [ $# -eq 1 ]; }

or

! [ $# -eq 0 -o $# -eq 1 ]

The double-brace keyword is a bash expression, and will not work with other POSIX shells, but it has some benefits, as well, such as being able to do these kinds of operations more readably.

Of course, there are a lot of ways to test the number of arguments passed. The mere existence of $2 will answer your question, as well.

kojiro
  • 74,557
  • 19
  • 143
  • 201
13

In my case I got this error with the following:

if [ $# -eq 1]; then

Notice that there is no space between the 1 and the ]. Adding a space fixed the error.

e-e
  • 1,071
  • 1
  • 11
  • 20
  • Adding space works for me. In my case I used command like `[ ! -d "report-file"] && mkdir report-file && chmod 777 report-file` and it throws error: -bash: [: missing ]'. After adding space after folder name [ ! -d "report-file" ]` it works. – akshay_sushir Oct 31 '22 at 06:24
0

In some cases this error happens even if everything looks fine as @kojiro mentioned above. in such cases a simple and proper line-break will help. if-statement where you are checking with || should have a line-break from it's prior-line of code.

Nani
  • 1,148
  • 3
  • 20
  • 35