Search code examples
shellfishnautilus

fish shell how to tokenize variable to a list


It's weird that others are complaining that fish is always splitting their variables to lists. But to me it's just having the multiline variable as a single string.

I'm trying to write a nautilus script. The nautilus should set a variable called $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS with the selected files separated with newlines.

I'm trying to get them as a list to loop over them with fish. But they just behave as a single element.

set -l files $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS

for i in (seq (count $files))
   echo (count $files) >> koko
end

and the file koko now shows the number 1.


Solution

  • Fish does not split variables after they have been set (this is known as "word splitting").

    What it does, however, do is split command substitutions on newlines, so

    set files (echo $files)
    

    will work.

    Or, if you wish to make it clear that you're doing this to split it, you can use string split like

    set files (string split \n -- $files)
    

    which will then end up the same (because currently string split only adds newlines), but looks a bit clearer. (The "--" is the option separator, so nothing in $files is interpreted as an option)

    The latter requires fish >= 2.3.0.