git !alias 可在 bash 和 Powershell 中使用

git !alias that would work in both bash and Powershell

您将如何实现执行外部命令并在 bash 和 Powershell 中工作的 git 别名?

我目前为 bash(在我的 .bash_profile 中)和 Powershell(在 profile.ps1 中)设置了一个 gitPrune 别名,它清理了分支不再需要:

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

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

这样,我可以从 git-bash(在 Windows 上)和 Powershell 中 gitPrune。现在我想将它移到我的 .gitconfig 中,以便与其他 git 相关的别名保持一致。但是,无论我是否打开了 Powershell 控制台或 git-bash 终端,都将使用相同的 .gitconfig。如何使用 git-config "external command" 语法实现此 "dual" 命令?

[alias]
    myPrune = "! ..."

当git使用shell执行别名时,shell used is a fixed compile-time option. It's generally going to be /bin/sh.

因此,您无需担心结果不同,只需使用 bash 别名中的语法即可,而不必担心功率 shell。演示:

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

$ bash -c 'git shellpath'
/bin/sh
$ pwsh -c 'git shellpath'
/bin/sh