Bash functional: Difference between revisions

From wikinotes
Line 12: Line 12:
= Map =
= Map =
<blockquote>
<blockquote>
{{ NOTE |
If your callable accepts parameter as stdin, you don't need map (ex. grep/sed work just fine from stdin).<br>
}}
<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">
map() {
map() {
     # ARGS:
     # Call callable/params($*), passing each each STDIN line as the last parameter
    #  $1:    name of function to call
    #  STDINthe item to pass as argument to function
     local input
     local input


Line 28: Line 30:
<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">
print_if_divisible_by_2() {
print_if_divisible_by_2() {
     # prints number if divisible by 2
     if [ $(($1 % 2)) -eq 0 ] ; then
    [ $(($1 % 2)) -eq 0 ] && echo $1
        echo "$1:yes"
    else
        echo "$1:no"
    fi
}
}


cat << EOF | map print_if_divisible_by_2
echo {1..4} | tr ' ' '\n' | map print_if_divisible_by_2
1
#> 1:no
2
#> 2:yes
3
#> 3:no
4
#> 4:yes
EOF
 
#> 2
#> 4
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Map -->
</blockquote><!-- Map -->

Revision as of 19:07, 11 December 2022

Filter

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

Map

NOTE:

If your callable accepts parameter as stdin, you don't need map (ex. grep/sed work just fine from stdin).

map() {
    # Call callable/params($*), passing each each STDIN line as the last parameter
    local input

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

Example

print_if_divisible_by_2() {
    if [ $(($1 % 2)) -eq 0 ] ; then
        echo "$1:yes"
    else
        echo "$1:no"
    fi
}

echo {1..4} | tr ' ' '\n' | map print_if_divisible_by_2
#> 1:no
#> 2:yes
#> 3:no
#> 4:yes

Reduce