6

How would you implement a git alias that executes external commands, and works from both bash and Powershell?

I currently have a gitPrune alias set up for both bash (in my .bash_profile) and Powershell (in profile.ps1), which cleans up branches that are no longer needed:

# bash
alias gitPrune="git remote prune origin; git branch --merged | grep -vEe '^\*| master$' | sed 's/.*/git branch -dv \0/e'"    

# Powershell
function gitPrune { git remote prune origin; git branch --merged | Select-String -NotMatch '^\*| master$' | %{git branch -dv $_.ToString().Trim()} }

This way, I can gitPrune from both git-bash (on Windows) and from Powershell. Now I'd like to move this into my .gitconfig, to keep together with other git-related aliases. However, the same .gitconfig will be used regardless of whether I have a Powershell console or the git-bash terminal open. How do I implement this "dual" command using the git-config "external command" syntax?

[alias]
    myPrune = "! ..."
4
  • Git does not use your shell. It start its own instead. Commented Jul 5, 2018 at 9:53
  • Sure, but why is that important? Commented Jul 5, 2018 at 15:04
  • 2
    Yes, your shell is not important. Git will spawn its own shell to execute shell command. And it would be the same shell regardless the shell you use (if any) to execute Git. Commented Jul 5, 2018 at 21:19
  • Ah, I get it. Thanks. Commented Jul 10, 2018 at 11:39

1 Answer 1

1

When git uses the shell to execute an alias, the shell used is a fixed compile-time option. It's generally going to be /bin/sh.

So you don't need to worry about the results being different and can just use the syntax you had in your bash alias without worrying about powershell. To demonstrate:

$ cat .git/config
[alias]
    shellpath = !pid=$$ && ps -o comm= $pid

$ bash -c 'git shellpath'
/bin/sh
$ pwsh -c 'git shellpath'
/bin/sh
Sign up to request clarification or add additional context in comments.

1 Comment

There's this peculiar case when you try to pipe some xargs, since there is no xargs in Windows and yet if git uses a compiled shell, it tries to reach for an xargs program and fails. using powershell style @().foreach collecting also fails since it's not how /bin/sh works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.