How to format "if" statement (conditional) on multiple lines in bash?

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?


Solution 1:

Use backslashes.

if [ $(do_something "arg1") ] || \
   [ $(do_something "arg2") ] || \
   [ $(do_something "arg3") ]
then
  echo "OK"
else
  echo "NOT OK"
fi

EDIT

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

That's not possible in only one if statement. Instead you can use a for loop that iterates over the arguments and evaluates them separately. Something like:

do_something() {
  for x in "$@"
  do
    if [need to do something on $x]
    then
      do it
    else
      echo "no action required on $x"
    fi
  done
}

Solution 2:

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

Solution 3:

The correct syntax is:

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

\ is used to tell the shell a command continues in the next line.

EDIT: I think this should do what you want:

#!/bin/bash

do_something() {
  if [need to do something on $1]
  then
    do it
    echo "OK"
  else
    echo "NOT OK"
  fi
}

do_something "arg1"
do_something "arg2"
do_something "arg3"