Escaping shell command in git alias

I have this command that deletes all local branches that are not in the repo anymore, which I’m trying to add in the .gitconfig:

git checkout master && git fetch -p && git branch -l | sed 's/* master//' > /tmp/gitlocal.txt && git branch -r | sed 's/origin\///' > /tmp/gitremote.txt && grep -Fxv -f /tmp/gitremote.txt /tmp/gitlocal.txt | xargs git branch -D

I’m trying to put it as an alias, but I’m getting some escaping problems

  • git show difference between commit messages
  • GCommit doesn't work with fugitive.vim under windows xp?
  • Will git prune a commit that is branchless but is tagged?
  • clone specific commit bitbucket
  • Why does tracking branch create a new remote branch?
  • Find the latest file(s) added to a git repository with name(s) matching a given wildcard pattern
  • cleanbranches = "!f() { git checkout master && git fetch -p && git branch -l | sed 's/* master//' > /tmp/gitlocal.txt && git branch -r | sed 's/origin\///' > /tmp/gitremote.txt && grep -Fxv -f /tmp/gitremote.txt /tmp/gitlocal.txt | xargs git branch -D; }; f"
    

    After some trial and error, I’ve concluded that

    sed 's/origin\///'
    

    is making the alias break. If I remove this part, the commands are executed (but it’s just deleting every branch, instead of keeping the one still on the repo), and have no errors

    Any help on how I can escape ?

    Extra, but not necessary, if you could explain what that part of the alias is doing and why there are 3 slashes?

  • Is it possible to switch between GIT commits?
  • git-svn merges and commit details
  • Using Git, if some commits are lost, how to view it or get it back?
  • Not all files added to Git repository
  • How to get the current branch name in Git?
  • Why can't I add this directory to git?
  • One Solution collect form web for “Escaping shell command in git alias”

    You can rewrite sed 's/origin\///' using different separator, for example, sed 's|origin/||' (this command removes substring origin/ from its input).

    So the alias can be set up using:

    git config --global alias.cleanbranches '!git checkout master && git fetch -p && git branch -l | sed "s/* master//" > /tmp/gitlocal.txt && git branch -r | sed "s|origin/||" > /tmp/gitremote.txt && grep -Fxv -f /tmp/gitremote.txt /tmp/gitlocal.txt | xargs git branch -D'
    

    I don’t recommend editing .gitconfig directly, because it’s hard to get the escaping right. I also removed function wrapper (f() { ...; }; f), because I don’t think it’s required.

    I would also not recommend using git branch -D in such automated way (I did not review the commands inside the alias, so I can’t tell whether this is safe).

    Git Baby is a git and github fan, let's start git clone.