Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an array from a function with Fish Shell

Tags:

fish

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?

like image 674
Olivier Refalo Avatar asked Nov 07 '13 11:11

Olivier Refalo


1 Answers

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.

like image 124
ridiculous_fish Avatar answered Sep 24 '22 11:09

ridiculous_fish