Reputation: 22379
I've defined this function (with some debugging printouts):
listcontains() {
for item in $1
do
echo $2 = $item ?
if [ "$2" == "$item" ]; then
echo YES!
return 1;
fi
done
echo NO!
return 0
}
And I'm using it like this:
list="1 2"
if listcontains "$list" 3; then echo Y; else echo N; fi
I'm expecting N, but the result is Y, and the debug output makes it even more strange:
3 = 1 ?
3 = 2 ?
NO!
Y
What did I do wrong?
Upvotes: 0
Views: 45
Reputation: 35950
In shell, you use 0
to denote true
(and some positive number, i.e. 1
, to denote false
). It's the same notion as for scripts exit values - in unix world, 0
means success.
So to fix, just reverse return values:
listcontains() {
for item in $1
do
echo $2 = $item ?
if [ "$2" == "$item" ]; then
echo YES!
return 0;
fi
done
echo NO!
return 1
}
Example:
$ list="1 2"
$ if listcontains "$list" 3; then echo Y; else echo N; fi
3 = 1 ?
3 = 2 ?
NO!
N
$ list="1 3"
$ if listcontains "$list" 3; then echo Y; else echo N; fi
3 = 1 ?
3 = 3 ?
YES!
Y
Upvotes: 1