Bora M. Alper
Bora M. Alper

Reputation: 3852

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!

Upvotes: 4

Views: 851

Answers (2)

faho
faho

Reputation: 15984

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.

Upvotes: 5

glenn jackman
glenn jackman

Reputation: 247092

This is where you need eval.

$ set s "program argument escaped\ argument.txt -o 'another escaped.output'"
$ eval set v $s
$ printf "%s\n" $v
program
argument
escaped argument.txt
-o
another escaped.output

Upvotes: 4

Related Questions