Reputation: 198
isCat() [[ $word = "cat" ]]
isDog() [[ $word = "dog" ]]
isFish() [[ $word = "fish" ]]
isAny() { if isCat || isDog || isFish; then return 0; else return 1; fi }
I would like to simplify the 'isAny' function to something like:
isAny() [[ isCat || isDog || isFish ]]
but I'm not finding out how to. The above attempt is incorrect because 'isAny' is true when all the other functions evaluate to false. I'm using these functions in this way:
if isCat; then
echo "cat"
fi
if isAny; then
echo "any"
fi
Upvotes: 0
Views: 63
Reputation: 295619
The reason
isAny() [[ isCat || isDog || isFish ]]
...is always true, even if the functions all return false, is that it's checking whether "isCat"
, "isDog"
, and "isFish"
are non-empty strings -- which of course they always are -- rather than running them as functions.
If you're literally trying to do a comparison against several fixed tokens, a case
statement is the conventional (and POSIX-compliant) way to do this:
case $word in
cat|dog|fish) return 0;;
*) return 1;;
esac
That said, if this was a nonliteral example:
isAny() { isCat || isDog || isFish; }
...is the easiest way to write your function. Because it's not in [[ ]]
, it's actually running shell commands (your defined functions), rather than interpreting content as extended-test
syntax.
Upvotes: 3
Reputation: 77137
A shell function will return the exit status of the last command it ran. Thus…
IS_ANY() { IS_CAT || IS_DOG || IS_FISH; }
will do the trick.
Upvotes: 2