Bash functional: Difference between revisions
From wikinotes
(Created page with "= Filter = <blockquote> <source lang="bash"> # filters out results not matching 'grep foo' find . \ | while read line; do \ echo $line | grep foo && echo "$line"; \ do...") |
(→Map) |
||
Line 12: | Line 12: | ||
= Map = | = Map = | ||
<blockquote> | <blockquote> | ||
<syntaxhighlight lang="bash"> | |||
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 | |||
} | |||
</syntaxhighlight> | |||
Example | |||
<syntaxhighlight lang="bash"> | |||
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 | |||
</syntaxhighlight> | |||
</blockquote><!-- Map --> | </blockquote><!-- Map --> | ||
Revision as of 18:47, 11 December 2022
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