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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With