【问题标题】:Using grep and xargs with git to delete multiple branches at onceUsing grep and xargs with git to delete multiple branches at once
【发布时间】:2022-12-02 00:24:08
【问题描述】:

I've been using some of the Linux tooling on my Windows machine for a little while now, since it comes with the git installation and it's a ton of fun to use. I've been particularly enamored with this command, which should theoretically allow me to delete all my extraneous git branches in one go:

git branch | grep -v 'master' | xargs git branch -d

A while ago, however, this stopped working. Instead I get a series of error messages for each branch along the following lines:

error: branch 'extraneous-branch-1?' not found.
error: branch 'extraneous-branch-2?' not found.
error: branch 'extraneous-branch-3?' not found.
...

Note that the question marks are not part of my branch names - those are apparently being added somehow when the values are piped from grep to xargs. When I run xargs in interactive mode to try to see what it's actually producing, I get an output that looks like this:

git branch -d 'extraneous-branch-1'$'\r' 'extraneous-branch-2'$'\r' 'extraneous-branch-3'$'\r' ...

It seems as if grep is piping the end-of-line and carriage-return entries as part of each match, though I don't know how to prevent it from doing that. What baffles me is that I definitely remember this working before - I have no idea what would have changed. Truthfully I know barely anything about the Linux command line tools, so I wouldn't be surprised if there's something obvious I'm overlooking here. Appreciate any advice either way.

Edit

When I run git branch | cat -A, I get the following result:

 extraneous-branch-1$
 extraneous-branch-2$
 extraneous-branch-3$

【问题讨论】:

  • Can you show output of git branch | cat -A ?
  • Interesting. I'll update my post with the results I got.
  • It's not + cat, it's pipe: |. Fixed.
  • ok now try: git branch | command grep -vF 'master' | cat -A
  • Ah rats, it appears I don't have command - when I try that I get 'command' is not recognized as an internal or external command, operable program or batch file.

标签: bash git cmd grep xargs


【解决方案1】:

Thanks to anubhava for pointing me in the right direction here. It appears grep is returning a bunch of non-printing characters that are visible when you run git branch | cat -A. It turns out just adding cat in there eliminates all those characters. Now it works perfectly.

git branch | grep -v master | cat | xargs git branch -d

a bit more verbose than before, but I'm not complaining.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-07
    • 2021-11-23
    • 2022-12-02
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    相关资源
    最近更新 更多