简体   繁体   中英

Simplify bash if statement with or operators

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM