8

I'm trying to append an element to an array.

What I tried is:

 for i in (seq 10)
            set children $children $line[$i]
 end

but that does not add a new element. It creates a single variable containing all of children then a space and $line[$i].

3
  • What you are doing is actually correct. Why do you believe it is wrong? echo $children will show lists as space-separated, so try something like string escape -- $children instead.
    – faho
    Apr 25, 2018 at 17:24
  • What @faho said. Also printf '|%s|\n' $children or, if you're using a new enough version set --show children. Apr 25, 2018 at 17:27
  • aah thank you guys. the problem was I echoed $children at the end which made it a single line. I solved it by using tr to replace spaces with newlines like so echo $children | tr ' ' \n Apr 25, 2018 at 18:45

1 Answer 1

10

Using fish version 2.7.1-1113-ge598cb23 (3.0 pre-alpha) you can use set -a (append) or set -p (prepend).

set -l array "tiny tim" bob
set -l children joe elias matt

echo $children
for i in (seq 2)
    set -a children $array[$i]
end
echo $children

Output:

joe elias matt
joe elias matt tiny tim bob

You could also use the string command which should work on most recent versions of fish.

set -l array "tiny tim" bob
set -l children joe elias matt

echo $children
for i in (seq 2)
    set children (string join " " $children $array[$i])
end
echo $children

Output:

joe elias matt
joe elias matt tiny tim bob
2
  • 3
    While this does give seemingly correct output, some inspection reveals that using the string command gives a single string rather than an array (i.e. echo $children[2] gives the empty string)
    – HackerBoss
    Feb 24, 2019 at 3:34
  • 1
    Note that @HackerBoss's comment about it not giving the expected output only applies to the second form; the -a switch works just fine. Mar 17, 2021 at 12:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.