wsalame
wsalame

Reputation: 130

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

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?

Upvotes: 4

Views: 300

Answers (1)

Roman
Roman

Reputation: 6657

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).

Upvotes: 3

Related Questions