Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[: missing `]' in bash script

Tags:

bash

sh

brackets

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?

like image 943
Majora320 Avatar asked Feb 09 '16 00:02

Majora320


2 Answers

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.

like image 144
kojiro Avatar answered Sep 22 '22 17:09

kojiro


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.

like image 44
e-e Avatar answered Sep 18 '22 17:09

e-e