Last active
May 22, 2019 04:59
-
-
Save yookoala/33070d4dd719d4ee908fed6c7bbe2cc3 to your computer and use it in GitHub Desktop.
A snippet for more functional style bash scripts
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 | |
# map the data output from CLI tools like ls or find | |
# to execute action on each result. | |
# | |
# Example Usages: | |
# map <FUNCNAME or CLI COMMAND> "$(find ./some-folder -mindepth 1)" | |
# or | |
# find ./some-folder -mindepth 1 | map <FUNCNAME or CLI COMMAND> | |
# | |
map() { | |
local ACTION=$1 | |
local IFS=$(echo -en "\n\b") | |
# test argument 2 with parameter exapnsion | |
if [ -z ${2+x} ]; then | |
# argument 2 not set | |
# read from STDIN | |
while read -r INPUT; do | |
$ACTION $INPUT | |
done | |
else | |
# argument 2 is set | |
# read from DATA | |
for f in $2; do | |
$ACTION $f | |
done | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The below one liner would have similar effects:
Options explained for xargs:
-i
specifies to use replacement string (default "{}
").-d
specifies the delimiter between input items. The argument-d "\n\b"
would work properly withfind
andls
output that has file / folder names that with space.