Question

I am trying to return an array from a function. The code below doesn't work.

function testArray
   echo 1 2 3 4
end

set r (testArray)

echo $r[2]
# error

What is the proper way to return multiple values from a function using fish shell?

Was it helpful?

Solution 2

As explained by ridiculous_fish you can use native line-splitting mechanism.

result of a command substitution becomes a list by splitting on newlines ($IFS)

So

  1. list one item per line ;
  2. then capture that in a command substitution.

Listing

function __list_public_keys
    for key in ~/.ssh/*.pub
        echo $key
    end
end
output
$ __list_public_keys
/home/ed8/.ssh/id_rsa.blabla.pub
/home/ed8/.ssh/id_rsa.pub
/home/ed8/.ssh/id_rsa.test.pub

Capturing

function __add_keys
    set keys (__list_public_keys)

    echo "[" $keys "]"
end
output
$ __add_keys
[/home/ed8/.ssh/id_rsa.blabla.pub] [/home/ed8/.ssh/id_rsa.pub] [/home/ed8/.ssh/id_rsa.test.pub]

OTHER TIPS

The result of a command substitution becomes a list by splitting on newlines (technically the contents of $IFS, but modifying IFS is discouraged).

So you could replace spaces with newlines, perhaps with tr:

function testArray
   echo 1 2 3 4
end
set r (testArray | tr ' ' \n)
echo $r[2]

Or modify the function to just output newlines directly:

function testArray
   echo \n1\n2\n3\n4
end
set r (testArray)
echo $r[2]

https://github.com/fish-shell/fish-shell/issues/445 tracks better mechanisms for generating lists.

I don't think this is possible yet. Compare this issue on GitHub.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top