Shell: Using function with parameters in if

When using if [ ... ] you are actually using the [ utility (which is the same as test but requires that the last argument is ]).

[ does not understand to run your function, it expects strings. Fortunately, you don't need to use [ at all here (for the function at least):

if [ "$docheck" -eq 1 ] && notContainsElement "$fruit" "${blacklist[@]}"; then
  ...
fi

Note that I'm also checking the integer first, so that we may avoid calling the function at all if $docheck is not 1.

This works because if takes an arbitrary command and decides what to do from the exit status of that command. Here we use a [ ... ] test together with a call to your function, with && in-between, creating a compound command. The compound command's exit status would be true if both the [ ... ] test and the function returned zero as their exit statuses, signalling success.

As a style note, I would not have the function test whether the array does not contain the element but whether if does contain the element, and then

if [ "$docheck" -eq 1 ] && ! contains "$fruit" "${blacklist[@]}"; then ...

Having a function test a negative will mess up logic in cases where you do want to test whether the array contains the element (if ! notContainsElement ...).


try

if notContainsElement "$fruit" "${blacklist[@]}" && test "$docheck" = 1
then
  • -a option is neither a shell or a test option

here you have two part test

notContainsElement "$fruit" "${blacklist[@]}"
test $docheck = 1 ## or [ $docheck = 1 ]

you link then in if using

if cmd1 && cmd2

as pointed out -a is a test option, but can only be used with other test option, thus you can use

if [ "$a" -lt "$b" -a "$a" -lt "$c" ]

to test that $a is lower than both $b and $c, but you cannot used other command within test scope.