Majora320 February 2016

[: missing `]' in bash script

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?

Answers


kojiro February 2016

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.

Post Status

Asked in February 2016
Viewed 3,106 times
Voted 5
Answered 1 times

Search




Leave an answer