Search code examples
fish

What to do if fish can't use variable as value in for grammar


For example

set -g hi "lol lol 123 321"

For I in $hi
    echo $hi
end

It directly output $hi


Solution

  • You have numerous issues here:

    1. It's for, not For.
    2. $hi is a variable with one element, so running a for-loop doesn't make a lot of sense here. Presumably you want to set it like set -g hi lol lol 123 321 without the quotes
    3. Inside the (presumed) for-loop, you are printing $hi, not the loop variable - this should probably be echo $I.

    Let's replace $hi with its value here:

    for I in "lol lol 123 321"
        echo "lol lol 123 321"
    end
    

    See how that might print lol lol 123 321 once? Fish does not do word-splitting, so if you set $hi to "lol lol 123 321", that's the value that will be used when you use the variable without quotes. So it's like we've just done here.

    There is no way fish can't "use this variable as value in for grammar". It uses the variable as you told it.

    What I think you meant was

    set -g hi lol lol 123 321
    
    for I in $hi
       echo $I
    end
    

    which will print

    lol
    lol
    123
    321
    

    See how this sets $hi without quotes, so it's now four separate elements? Also it uses the actual loop variable in the loop.