Last active
June 4, 2022 00:49
A set of functional-ish highlevel functions implemented in bash.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# A collection of high-level-ish functions for | |
# bash pipeline operations. | |
# breakdown the output of ls or find into one | |
# item per line in STDOUT for pipeline. | |
# | |
# Usage: | |
# ls . | breakdown | |
breakdown() { | |
local IFS=$(echo -en "\n\b") | |
# argument 2 is set | |
# read from DATA | |
for f in $1; do | |
echo "$f" | |
done | |
} | |
# map the STDOUT from CLI tools like ls or find | |
# to execute action on each result. | |
# | |
# Usage: | |
# some-stdout-operation | map <FUNCNAME or CLI COMMAND> | |
map() { | |
local ACTION="$1" | |
while read -r INPUT; do | |
$ACTION $INPUT | |
done | |
} | |
# filter the STDOUT from CLI tools like ls or find | |
# to check all items if matches the testing function or cli tools. | |
# | |
# If pass, the item will be echo to STDOUT. | |
# | |
# Usage: | |
# some-stdout-operation | filter <FUNCNAME or CLI COMMAND> | |
filter() { | |
local TEST="$1" | |
while read -r INPUT; do | |
if $TEST "$INPUT"; then | |
echo "$INPUT" | |
fi | |
done | |
} | |
# accumulate the STDOUT of FUNC or CLI tools with the | |
# STDOUT of pipeline to for ACC then echo. | |
# | |
# Usage: | |
# some-stdout-operation | reduce <FUNCNAME or CLI COMMAND> | |
reduce() { | |
local OP="$1" | |
# initialize ACC from first input or argument 2 | |
if [ ! -z ${2+x} ]; then | |
local ACC="$2" | |
else | |
read -r INPUT | |
local ACC="$INPUT" | |
fi | |
# read from STDIN | |
while read -r INPUT; do | |
ACC=$($OP "$ACC" "$INPUT") | |
done | |
echo $ACC | |
} | |
# export functions | |
export -f breakdown | |
export -f map | |
export -f filter | |
export -f reduce |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
source highlevel_func.sh | |
hello () { | |
echo "hello $1" | |
} | |
isdir() { | |
if [ -d "$1" ]; then | |
return | |
fi | |
false | |
} | |
concat2() { | |
echo "$1; $2" | |
} | |
# Usage: simple mapping | |
find ./temp -mindepth 1 | map hello | |
# Usage: filter find outputs | |
find ./temp -mindepth 1 | filter isdir | reduce concat2 | |
# Usage: breakdown find / ls output for use | |
breakdown "$(find ./temp -mindepth 1)" | map hello | |
# Usage: advanced filter, map and sort | |
find ./temp -mindepth 1 | filter isdir | map hello | sort -r |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment