Bash functional

From wikinotes
Revision as of 18:47, 11 December 2022 by Will (talk | contribs) (→‎Map)

Filter

# filters out results not matching 'grep foo'
find . \
  | while read line; do \
    echo $line | grep foo && echo "$line"; \
  done

Map

map() {
    # ARGS:
    #  $1:     name of function to call
    #  STDIN:  the item to pass as argument to function
    local input

    while read -r input; do
        "$[@]" "${input}"
    done
}

Example

print_if_divisible_by_2() {
    # prints number if divisible by 2
    [ $(($1 % 2)) -eq 0 ] && echo $1
}

cat << EOF | map print_if_divisible_by_2
1
2
3
4
EOF

#> 2
#> 4

Reduce