Categories
Linux Mastering Development

Why does my filter function in Bash not work?

I wrote a filter / select function that takes a function and a stream as input. It should yield a new array of ( 2 4 ). However, my result is nothing. I suspect it has something to do with the IFS.

# func int -> bool
is_even () { (( $1 % 2 == 0 )) ;}

# func func -> int
filter () {
  local function_to_apply=$1
  local arg

  while read -r arg; do
    $function_to_apply $arg && echo $arg
  done;:
}

# int array
integers=( 1 2 3 4 )  
result=$(echo "${integers[*]}" | filter is_even)
declare -p result

Output is a string ""

declare -- result=""

Expected Output is an array of ( 2 4 )

declare -a result ='([0]="2" [1]="4")'

Give credit where credit is due:

http://www.binaryphile.com/bash/2018/07/26/approach-bash-like-a-developer-part-1-intro.html

Leave a Reply

Your email address will not be published. Required fields are marked *