jaeyong
jaeyong

Reputation: 9363

Checking the number of param in bash shell script

I use for checking the number of params in bash shell as follows:

#! /bin/bash
usage() {
    echo "Usage: $0 <you need to specify at least 1 param>"
    exit -1
}
[ x = x$1 ] && usage

where, if [ x = x$1 ] condition is not satisfied, execute usage. Here, my question is, I never really think about the expression [ x = x$1 ] which looks a lot like a condition expression. Is x counted as a literal? and how come can we use = for comparison. Typically should it be something like ==?

Could anybody please fill the void here?

Upvotes: 2

Views: 771

Answers (3)

janos
janos

Reputation: 124648

[ x = x$1 ] is error prone, don't use it. Do this instead [ "$1" ]

The difference is that if $1 contains a space or other special characters, your script will crash, for example:

$ a='hello world'
$ [ x = x$a ] && echo works
-bash: [: too many arguments

To fix this you could do [ x = x"$1" ], but [ "$1" ] is shorter, so what's the point.

[] expressions are used extensively in shell scripts, I recommend to read help test. The [ is a synonym for the "test" builtin, but the last argument must be a literal ], to match the opening [. In there you will find the explanation of the differences between = and == operators.

Finally, literal text in conditions is evaluated to true if not empty. Some more examples:

[ x ]       # true
[ abc ]     # true
[ a = a ]   # true
[ a = x ]   # false
[ '' ]      # false
[ b = '' ]  # false

Also common gotchas are these:

[ 0 ]       # true
[ -n ]      # true
[ -blah ]   # true
[ false ]   # true

These are true, because 0, -n, false or anything being the only argument, they are treated as literal strings, and so the condition evaluates to true.

Upvotes: 0

simryang
simryang

Reputation: 98

[ x = y ] condition is for comparing strings. (just once =)

x$1 means concatenating two string x and $1.

So, if $1 is empty, x$1 equals x, and [ x = x ] will be true as a result.

Upvotes: 1

rendon
rendon

Reputation: 2363

Use $# to count the number of parameters and use the OR operator instead of the AND so that usage() only gets executed if the first condition fails.

#! /bin/bash
usage() {
    echo "Usage: $0 <you need to specify at least 1 param>"
    exit -1
}
[ x = $# ] || usage

Upvotes: 0

Related Questions