Jazzepi
Jazzepi

Reputation: 5490

xargs with git checkout fails with pathspec error

When I run the below command

git branch | grep solution- | cut -c 3- | xargs git checkout

I get this error output

error: pathspec 'solution-2' did not match any file(s) known to git.
error: pathspec 'solution-3' did not match any file(s) known to git.

When I run the below command

git checkout solution-1 && git checkout solution-2 && git checkout solution-3

I get this correct output

Switched to branch 'solution-1'
Your branch is ahead of 'master' by 1 commit.
  (use "git push" to publish your local commits)
Switched to branch 'solution-2'
Your branch is ahead of 'master' by 1 commit.
  (use "git push" to publish your local commits)
Switched to branch 'solution-3'
Your branch is ahead of 'master' by 3 commits.
  (use "git push" to publish your local commits)

I don't understand why git is failing on the xargs version.

Finally, just to prove that xargs is getting the correct arguments if I run git branch | grep solution- | cut -c 3- | xargs echo I get solution-1 solution-2 solution-3 which is what I expect.

Upvotes: 1

Views: 1228

Answers (1)

Prateek Joshi
Prateek Joshi

Reputation: 4067

From your question I conclude that you have a git repo with 3 branches solution-1, solution-2 & solution-3.

Now when you run the below command

git checkout solution-1 && git checkout solution-2 && git checkout solution-3

you get correct output because the git checkout gets a valid branch name each time (it ran 3 time with different branch name).

Now, lets see why you get error when running below command,

git branch | grep solution- | cut -c 3- | xargs git checkout

Running the above command is equivalent to running ,

git checkout solution-1 solution-2 solution-3

which will prompt you the same error. This is because git checkout only executed one time with solution-1 as branch name and solution-2 & solution-3 as file names.

Now, you actually want to switch branches one by one for each argument from xargs. To do this you can run the below command.

git branch | grep solution- | cut -c 3- | xargs -d '\n' -n1  git checkout

Upvotes: 2

Related Questions