Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string into shell arguments

I'm interested how is parsed the bash input into arguments.

For example, by using process.argv we get an array of strings in NodeJS (but this is language agnostic).

My question is how can I parse an input like "node foo.js --foo "bar baz" -b foo" into an array like process.argv (or the equivalent in other languages) returns (e.g. ["node", "foo.js", "--foo", "\"bar baz\"", "-b", "foo"]?

Splitting by space is not enough (because of the quotes). Is it possible with some more complicated regex to handle the quotes and getting such an array?

like image 793
Ionică Bizău Avatar asked Jul 25 '26 22:07

Ionică Bizău


1 Answers

Using the shell-quote NPM package will handle this.

var parse = require('shell-quote').parse;
parse('node foo.js --foo "bar baz" -b foo');

[ 'node', 'foo.js', '--foo', 'bar baz', '-b', 'foo' ]
like image 91
James Thomas Avatar answered Jul 27 '26 11:07

James Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!