如何在PowerShell提示符中显示当前的git分支名称?

103

基本上我想要的是这个,但是用于PowerShell而不是bash。

我在Windows上通过PowerShell使用git。如果可能的话,我希望我的当前分支名称可以显示为命令提示符的一部分。


1
在 Git 2.22(2019 年第二季度)中,不要忘记 git branch --current - VonC
1
@VonC,命令是 git branch --show-current。不确定最初是否为 --current,但截至2023年,它已更改为前者。 - Jacques Mathieu
@JacquesMathieu 我同意,而且我参考的答案确实提到了 --show-current - VonC
12个回答

0

我使用了与@tamj0rd2上面提到的方法类似但更简单的方法。

打开:Microsoft.PowerShell_profile.ps1

首先添加:

function Get-GitBranch {
    if (Test-Path .git) {
        $branch = git rev-parse --abbrev-ref HEAD
        " [$branch]"
    }
}

添加第二个:

function prompt {
    $p = Split-Path -leaf -path (Get-Location)
    Write-Host "$p" -NoNewline
    Write-Host (Get-GitBranch) -NoNewline -ForegroundColor Yellow
    Write-Host "> " -NoNewline
    return " "
}

以下是结果: 输入图像描述

我是通过使用split-path来实现缩短字符串或目录路径的,因此总的提示是:
function prompt {
    $p = Split-Path -leaf -path (Get-Location)
    Write-Host "$p" -NoNewline
    Write-Host (Get-GitBranch) -NoNewline -ForegroundColor Yellow
    Write-Host "> " -NoNewline
    return " "
}

仅在存储库的根文件夹中工作! - Tobias Wollgam

0

这是我在 Windows 11 上使用终端应用程序的最简单方法。它适用于主题化的 PowerShell,在无样式的情况下工作,并在子目录中显示分支。

  1. 在 PowerShell 中运行 echo %profile
  2. 导航到文件或创建目录和文件(如果不存在)。我的文件位于此处:C:\Users\YourName\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
  3. 粘贴以下代码:
function prompt {
    $gitBranch = & git rev-parse --abbrev-ref HEAD 2>$null
    $promptString = "$PWD"
    
    if ($gitBranch) {
        $promptString += " ($gitBranch)"
    }
    
    "$promptString> "
}

我的最终结果与太阳能化的深色PowerShell主题: 输入图像描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接