Adham Zahran
Adham Zahran

Reputation: 2180

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.

Upvotes: 5

Views: 3187

Answers (2)

Ahmad Ismail
Ahmad Ismail

Reputation: 13942

If you want to split variable by space, then the command is:

set files (string split ' ' --no-empty -- $files)

Do not forget --no-empty.

Now you can also get individuals values by, for example:

if set -q files[1]
    echo files[1] $files[1]
end

if set -q files[2]
    echo files[2] $files[2]
end

...

Upvotes: 1

faho
faho

Reputation: 15984

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.

Upvotes: 15

Related Questions