Reputation: 17496
This is the code that produces the error:
#!/bin/bash
types=([i]=Info [w]=Warning [e]=Error [se]=Severe)
function isValidType
{
for type in "${!types[@]}"
do
if [ $1 == $type ]; then
return 0
fi
done
return 1
}
if [ isValidType "$msgType" -eq 1 ]; then # <---- error here
echo "Invalid type."
exit 0
fi
Upvotes: 1
Views: 3932
Reputation: 241721
The syntax of an if
statement is:
if <list>; then <list>; [elif <list>; then <list>;]* [else <list>;]? fi
where <list>
is any sequence of "pipelines" separated by ;
, &&
, or ||
. (A pipeline is one or more simple commands separated by |
symbols.)
The if
statement is evaluated by first executing the <list>
following the if
, and checking the return code, which will be the return code of the last simple command executed. Based on that, a decision is made as to whether to execute the <list>
following then
(if the first list succeeeded) or to proceed with the elif
tests and/or else
clause.
Nowhere in that syntax does a [
appear, and for a good reason. [
is actually a command. In fact, it is almost a synonym for test
; the difference is that [
insists that its last argument be ]
.
It's sometimes convenient to use [
(although it is almost always more convenient to use [[
, but that's an essay for another day), but it is in no way obligatory. If you just want to test whether a command succeeded or not, then do so:
if isValidType "$msgType"; then
# it's valid
else
# it's not valid
fi
If you only need to do something if it didn't work, use the !
special form:
if ! isValidType "$msgType"; then
# it's not valid
fi
Upvotes: 3
Reputation: 21
To check if a function returns true or not the proper way to do this is:
if [ !isValidType ]; then
// would throw a flag for any options passed that are invalid
// error output
fi
This works if isValidType will be either one or zero. I think the problem is in the you are checking the array.
Hope this helps.
Upvotes: -1
Reputation: 121387
Change this
if [ isValidType "$msgType" -eq 1 ]; then
to
isValidType "$msgType"
if [ $? -eq 1 ]; then
[
is the test
command which accepts an expression and doesn't work as you designed (Comparing the return value of the function).
Upvotes: 2