Shell – zsh: map command to array

arrayshell-scriptzsh

suppose you have an array a=(foo 'bar baz')

is there a more obvious way to apply a command/function to every array element and save the resulting strings into another array than this:

b=()
for e in $a; do
    b+=("$(my_cmd "$e")")
done

Best Answer

You can always declare a function for that:

map() {
  local arrayname="$1" cmd="$2" i
  shift 2
  eval "$arrayname=()"
  for i do
    eval "$arrayname+=(\"\$($cmd)\")"
  done
}

And use as:

$ a=(a '' bcd)
$ map b 'wc -c <<< "$i"' "$a[@]"
$ echo $b
2 1 4
Related Question