KurtPreston
KurtPreston

Reputation: 1152

How to pass git pathspec args using node spawn

I am trying to run the following shell command from within a Node application:

git grep MySearchString -- 'MyPathToSearchFor'

This command runs successfully using's node's child_process.exec:

exec("git grep MySearchString -- 'MyPathToSearchFor'") // succeeds!

However, I cannot get the command working using child_process.spawn, which requires arguments to be provided as an array of strings.

// Spawn works without the pathspec args:
spawn('git', ['grep', 'MySearchString']) // success! exits with code 0

// It fails when the pathspec args are provided:
spawn('git', ['grep', 'MySearchString', '--', "'MyPathToSearchFor'"]) // exits with code 1
spawn('git', ['grep', 'MySearchString', "-- 'MyPathToSearchFor'"]) // exits with code 128

How can I provide spawn the -- MyPathToSearchFor args? How should I translate the dash-dash and pathspec args into spawn parameters?

The problem seems related to quotes in the args, but I'm not sure how to handle those.

Upvotes: 0

Views: 53

Answers (1)

hlovdal
hlovdal

Reputation: 28180

The problem seems related to quotes in the args, but I'm not sure how to handle those.

Don't include quotes when you use the array argument form, e.g. just

spawn('git', ['grep', 'MySearchString', '--', "MyPathToSearchFor"]) 

With "'MyPathToSearchFor'" this makes git look for a file/directory whose name contains a single quote at the start and end (which in theory could exist, but rarely is what you have).

Upvotes: 2

Related Questions