Search code examples
shellfish

Splitting a String into Command Line Arguments


I am trying to split a sting from the command-line history of the user into command line arguments. For instance, I want to split

program argument escaped\ argument.txt -o 'another escaped.output'

into

$v[1]: program
$v[2]: argument
$v[3]: escaped argument.txt
$v[4]: -o
$v[5]: another escaped.output

I have tried every single possible solution that I could, but as fish quotes the variables automatically, none of my solutions worked.

Thanks!


Solution

  • Currently, there's no clean way to do this in fish.

    The best I could come up with is quite a hack:

    set s "program argument escaped\ argument.txt -o 'another escaped.output'"
    set oldcmd (commandline)
    commandline -r -- $s
    set v (commandline -o)
    commandline -r -- $oldcmd
    printf '%s\n' $v
    

    This abuses fish's commandline buffer, which does properly tokenize its contents.