Executing shell command in git alias
I have this command, which removes all local branches that are no longer in the repo that I am trying to add to .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 am trying to use it as an alias, but I am getting some escaping issues
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 came to the conclusion that
sed 's/origin\///'
makes an alias break. If I remove this part, the commands are executed (but it just deletes each branch, it doesn't save it to the repo) and has no errors
Any help on how I can escape?
Additionally, but not necessarily, if you could explain what this part of the alias does, and why there are three slashes?
You can overwrite sed 's/origin\///'
with a different delimiter, for example sed 's|origin/||'
(this command removes the substring origin/
from its input).
So the alias can be configured with:
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 is difficult to get an escape exit. I also removed the function wrapper ( f() { ...; }; f
) because I don't think it is necessary.
I would also not recommend using it git branch -D
in such an automatic way (I haven't looked at the commands inside the alias so I can't tell if it's safe).