You can use the following definition for a map
that is similar to the one found in many functional programming languages (eg python, haskell):
function map
{
local f="$1"
shift # consume first argument
for arg
do
"$f" "$arg" # assuming `f` prints a single line per call
done
}
Here's how you would use it in your example. Here some_cmd
may be a function defined locally:
function do_something
{
local IFS=$'\n' # only split on newlines when word splitting
result=($(map suffix "$@")) # split into lines and store into array
some_cmd "${result[@]}" # call some_cmd with mapped arguments.
}
function suffix
{
echo "$@".txt
}
do_something file1 file2 file3
Here's another variation of writing do_something
. Here some_cmd
must exist in $PATH
:
function do_something
{
map suffix "$@" | xargs some_cmd # call some_cmd with mapped arguments.
}
The main downside is that to use the result in another function, you need to mess around with IFS
to split on the newlines, or pipe into xargs; and if your map outputs contain newlines then either method fails completely.