Bash functional: Difference between revisions
From wikinotes
(→Map) |
(→Map) |
||
Line 23: | Line 23: | ||
# | # | ||
# EXAMPLE: | # EXAMPLE: | ||
# divisible_by_2() { | # divisible_by_2() { [ $(($1 % 2)) -eq 0 ] && echo "$1:yes" || echo "$2:no" } | ||
# echo {1..10} | tr ' ' '\n' | map divisible_by_2 | |||
# echo {1.. | |||
# #> 1:no | # #> 1:no | ||
# #> 2:yes | # #> 2:yes | ||
# #> | # #> ... | ||
# | # | ||
map() { | map() { |
Revision as of 19:35, 11 December 2022
Fancy loops that let you process things incrementally in a pipeline.
You'll almost never use these directly, but it might be inspiration for a more useful function.
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).
# Call callable/params($*), passing each each STDIN line as the last parameter # # EXAMPLE: # divisible_by_2() { [ $(($1 % 2)) -eq 0 ] && echo "$1:yes" || echo "$2:no" } # echo {1..10} | tr ' ' '\n' | map divisible_by_2 # #> 1:no # #> 2:yes # #> ... # map() { local input while read -r input; do "$@" "${input}" done }
Reduce
# callable/params must accept aggregate as 2nd-last param, and input as last param. # # EXAMPLE: # sum() { echo $(($1 + $2)) } # echo {1..10} | tr ' ' '\n' | reduce sum 0 # #> 55 # reduce() { local callable="${@:1:-1}" # all until last param local aggregate="${@[-1]}" # last param local input while read -r input; do aggregate="$("${callable[@]}" "${aggregate}" "${input}")" done echo "${aggregate}" }