I'm trying to figure out how to pass an argument with a function call from one function to another in the same bash script. Here's what I've got so far:
#!/usr/bin/env bash
# File: nevens.sh
function isiteven {
if (( "$element%2"=="0" ))
then
echo 1
fi
}
function nevens {
local result=0
for element in $@
do
if (( $(isiteven) == 1 )) # $(isiteven "$element")
then
result=$result+1
fi
done
echo $result
}
I've tried calling $(isiteven) and hard-coding $element in front of %2==0 inside the isiteven function. And I've tried passing the argument with the function call, either $(isiteven $element) or $(isiteven "$element"), but then I'm not sure what I should code in front of %2==0 to do the math.
I'm using Ubuntu 18.04 on a dedicated machine.
isiteven() { (( ( $1 % 2 ) == 0 )); }, then you could just writeif isiteven "$element"; then. That works because the default return value of a function is$?, andifbranches on return value. This is far more efficient than making your function write to stdout, and then needing to capture that stdout through use of a subshell (thus requiring FIFO setup and a fork to create the subshell).isiteven() (( $1%2 == 0 )).$?is a special parameter, not a variable -- but all the important aspects of your description were spot on). One bit of magic involved: For UNIX exit codes (as stored in$?), 0 is true and all other numbers are false (which is whyexit 1orreturn 1is used for errors in scripts), but in an arithmetic context 0 is false and all positive integers are true. This gets fixed up in how(( ))translates its numeric results to UNIX exit codes:(( 1 ))sets$?to 0, and the inverse.