0

I want to create a bash function that iterates over an array and returns 0 if an element passed as argument does not exist in the array, or 1 otherwise.

The following code however does not print anything on stdout.

function checkparsed {
  tocheck="$1"
  shift
  for item in $@
    do
      if [ "$item" = "$tocheck" ]; then
        return 0
      fi
  done
  return 1
}

mdfiles=('foo')
echo "$(checkparsed foo ${mdfiles[@]})"

2 Answers 2

1

You are capturing the output of the function (there is none).

To print 0 or 1, either echo them in the function directly (don't forget to return), or use echo $? after running the function.

To handle spaces and glob characters in elements in ${mdfiles[@]}, you should use double quotes:

for item in "$@"
# and
checkparsed foo "${mdfiles[@]}"
Sign up to request clarification or add additional context in comments.

Comments

1

This line is the issue:

echo "$(checkparsed foo ${mdfiles[@]})"

since your function is not echoing anything but you are returning values 0 or 1.

You actually need to check for $? for the return value from your function:

checkparsed foo ${mdfiles[@]}
echo $?

0

Or else use return value in condition evaluation:

checkparsed foo ${mdfiles[@]} && echo "found" || echo "not found"
found

checkparsed food ${mdfiles[@]} && echo "found" || echo "not found"
not found

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.