I have this function,

rpargs () {
    local i
    for i in "$@"
        test -e "$i" && args+="$(realpath --canonicalize-existing -- "$i")"  || args+="$i"

And I want to return args. The only ways I can think of are either to printf '%s\0' and then split it via expansion flags (0@), or to use a global like the code above.

  • Why do you want to return an array? Save the values in an array, and then use the array after the function is called. How is the function being used?
    – muru
    Commented Aug 12, 2019 at 6:57
  • @muru I use this function to turn existent paths in mpv's args to absolute paths, like this mpv() command mpv --sub-auto=fuzzy --fs --input-ipc-server "$mpv_ipc" "${(0@)$(rpargs "$@")}"
    – HappyFace
    Commented Aug 12, 2019 at 6:58

2 Answers 2


zsh's return builtin can only return a 32bit signed integer like the _exit() system call. While that's better than most other Bourne-like shells, that still can't return arbitrary strings or list of strings like the rc/es shells. The return status is more about returning a success/failure indication.

Here, alternatively, you can have the function take the name of the array to fill in as argument, like:

myfunc() {
  local arrayname=$1; shift
  # ...
  eval $arrayname'=("$elements[@]")'
  # the returned $? will be 0 here for success unless that eval command
  # fails.

myfunc myarray other args

Your printf '%s\0' approach wouldn't work for array elements that contain NULs.

Instead you could use the qq parameter expansion flag to quote elements on output, and the z (to parse quotes) and Q (to remove quoting) on input like:

myfunc() {
   # ...
   print -r -- ${(qq)elements}


But in addition to being less legible, it's also less efficient as it means forking a process and transfering the output of myfunc through a pipe in addition to the quoting/unquoting.


The idiomatic way is to just use the reply array. If you want, you can use the (P) flag and return in an array whose name is passed to the function:

myfunc() {
  local arrayname=${1:-reply}; shift
  # ...
  : ${(PA)arrayname::="${args[@]}"}
  • What's the A flag and ::=?
    – HappyFace
    Commented Apr 26, 2020 at 0:36
  • ::= is a force assignment (as opposed to ${name=word} where name is changed only if it was unset.) A converts the substitution into an array --- it's otherwise interpreted as a string. Stephane Chazelas's solution seems clearer to me; is there an advantage to this?
    – Michaël
    Commented Nov 27, 2020 at 19:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .