Search code examples
fish

Use multiple arguments stored in one variable in a command, in fish shell


I want to pass a bunch of parameters, stored in a variable, to a built in command, in a fish shell script. For example, like this:

set params "-h -d 1"
du $params

I was hoping the above would be equivalent to

du -h -d 1    

But, it is not. It results in an error: "du: illegal option --"

It does work if I just set params to -h or to -d 1 but not both.

The one workaround I found is to do

eval du $params

but this seems...wrong, excessive. Any cleaner way?


Solution

  • Just drop the quotes.

    The reason something like this works in POSIX shells (like bash) is because of "word splitting". When you use an unquoted variable, the value is substituted and then split along the characters in the IFS variable (typically tab, newline and space).

    In fish, just use an array to separate the elements in the first place. And as it happens, the only change needed is to remove the quotes:

    set params -h -d 1
    du $params