Skip to content

Instantly share code, notes, and snippets.

@yookoala
Last active May 22, 2019 04:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yookoala/33070d4dd719d4ee908fed6c7bbe2cc3 to your computer and use it in GitHub Desktop.
Save yookoala/33070d4dd719d4ee908fed6c7bbe2cc3 to your computer and use it in GitHub Desktop.
A snippet for more functional style bash scripts
#!/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
}
@yookoala
Copy link
Author

yookoala commented May 22, 2019

The below one liner would have similar effects:

find ./some-folder -mindepth 1 | xargs -i -d "\n\b" <FUNCNAME or CLI COMMAND> "{}"

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 with find and ls output that has file / folder names that with space.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment