Ubuntu – How to format “if” statement (conditional) on multiple lines in bash

bashsyntax

I have a Bash shell function that takes an argument and performs something on it if needed.

do_something() {
  if [need to do something on $1]
  then
    do it
    return 0
  else
    return 1
  fi
}

I want to call this method with several arguments and check if at least one of them succeeded.

I tried something like:

if [ do_something "arg1" ||
     do_something "arg2" ||
     do_something "arg3" ]
then
  echo "OK"
else
  echo "NOT OK"
fi

Also, I want to make sure that even if the first condition is true all other conditions will still be evaluated.

What is the correct syntax for that?

Best Answer

Run the commands first, then check if at least one of them succeeded.

#!/bin/bash

success=0
do_something arg1 && success=1
do_something arg2 && success=1
do_something arg3 && success=1

if ((success)); then
    printf 'Success! At least one of the three commands succeeded\n'
fi