Tomáš Zato
Tomáš Zato

Reputation: 53139

Integrate bash function return values

I have a function:

something() {
  if [ something ]; then
    echo "Something.";
    return 0;
  else
    echo "Not something.";
    return 1;
  fi
}

I call it in a loop, it actually validates some files and counts how many files were valid:

find . -type l | while read line ; do something "$line"; done

I need to count how many files were invalid, therefore how many times the function has returned 0. I was thinking about this:

INVALID=0;
find . -type l | while read line ; do INVALID=$(($INVALID + something "$line")); done

Needless to say, bash doesn't buy it. Note a few things:

Upvotes: 1

Views: 1008

Answers (1)

John Kugelman
John Kugelman

Reputation: 361605

The return value isn't directly available for arithmetic like that. You can either call the function then access $?, or branch based on the result of the function, like so:

INVALID=0
while IFS= read -r line; do
    something "$line" || ((++INVALID))
done < <(find . -type l)

Also note that you can't change variables inside a pipeline. Pipelines run in subshells and have their own copies of variables. You'll need to restructure the loop to run without a pipeline to have the changes to $INVALID stick: change find | loop to loop < <(find).

It's also a good idea to use read -r to disable backslash escapes and clear out $IFS to handle lines with leading whitespace better.

Upvotes: 4

Related Questions