改.bashrc,直观地判断本地repo是否有改动

preface

添加到.bashrc末尾

bash 复制代码
# ==================== Git 增强提示符 ====================              yan add may18
git_prompt() {
    if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
        return
    fi

    local git_root
    git_root=$(git rev-parse --show-toplevel 2>/dev/null)

    # 如果 HOME 本身是 git 仓库,则不显示,避免到处都有提示
    if [ "$git_root" = "$HOME" ]; then
        return
    fi

    local branch
    branch=$(git branch --show-current 2>/dev/null)

    if [ -z "$branch" ]; then
        branch="detached"
    fi

    local ahead=0
    local behind=0

    # 如果当前分支设置了 upstream,比如 origin/main
    if git rev-parse --abbrev-ref --symbolic-full-name @{u} >/dev/null 2>&1; then
        ahead=$(git rev-list --count @{u}..HEAD 2>/dev/null || echo 0)
        behind=$(git rev-list --count HEAD..@{u} 2>/dev/null || echo 0)
    fi

    local dirty
    dirty=$(git status --porcelain 2>/dev/null | wc -l)

    local cyan=$'\001\033[1;36m\002'
    local red=$'\001\033[31m\002'
    local yellow=$'\001\033[33m\002'
    local reset=$'\001\033[0m\002'

    local info="(${cyan}${branch}${reset}"

    if [ "$dirty" -gt 0 ]; then
        info+=" ${red}⚡${reset}"
    fi

    if [ "$ahead" -gt 0 ]; then
        info+=" ${yellow}↑${ahead}${reset}"
    fi

    if [ "$behind" -gt 0 ]; then
        info+=" ${red}↓${behind}${reset}"
    fi

    info+=")"

    printf " %s" "$info"
}

PS1='\u@\h:\w$(git_prompt) \$ '

一、解释脚本

1. ahead / behind 判断本地和远程repo版本

bash 复制代码
ahead=$(git rev-list --count HEAD..origin/"$branch" 2>/dev/null || echo 0)
behind=$(git rev-list --count origin/"$branch"..HEAD 2>/dev/null || echo 0)

含义是:

bash 复制代码
HEAD..origin/branch        # 远程有、本地没有 => 本地落后 behind
origin/branch..HEAD        # 本地有、远程没有 => 本地超前 ahead

2. 颜色代码

在 Bash 里,用:

bash 复制代码
$'\033[1;36m'

或者:

bash 复制代码
$'\e[1;36m'

可以显示颜色,更直观


二、更新.bashrc

然后执行:

bash 复制代码
source ~/.bashrc

显示效果大概是

如果你在 main 分支,本地比远程多 2 个提交:

bash 复制代码
ubuntu@:~/(main ↑2) $

如果本地落后远程 3 个提交:

bash 复制代码
ubuntu@:~/(main ↓3) $

如果有未提交修改:

bash 复制代码
ubuntu@:~/(main ⚡) $

如果既有修改,又超前又落后:

bash 复制代码
ubuntu@:~/(main ⚡ ↑1 ↓2) $

额外检查一下 upstream

如果你发现一直不显示 ↑ 或 ↓,可能是当前分支没有绑定远程分支。

进入项目目录后执行:

bash 复制代码
git branch -vv

如果看不到类似:

bash 复制代码
main abc1234 [origin/main] commit message

那就绑定一下:

bash 复制代码
git branch --set-upstream-to=origin/main main

或者首次推送时:

bash 复制代码
git push -u origin main

一、

相关推荐
未济4 天前
linux 配置环境变量
linux
傲世仙尊4 天前
目录即文件-Ext文件系统收尾篇
linux·c语言
虎头金猫4 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
_艾伦 耶格尔.4 天前
进程间通信
linux
Liuqy-054 天前
Linux IO编程——静态库、动态库
linux
彧azz4 天前
Linux 环境下 Redis 学习总结:数据类型、持久化、锁、事务、主从与缓存问题
linux·redis·笔记·学习·面试
-梅4 天前
linux(8) 软硬链接
linux·运维·服务器
Wang's Blog4 天前
Java 项目实战: 外卖平台-文件下载与ServletOutputStream回写浏览器
服务器·项目开发
AIgorithmGEEK4 天前
[Linux]线程三部曲(上):一个执行流的诞生——从操作系统一路拆到 pthread_create
linux·线程·pid
琥珀色糖4 天前
SimlpeHttp
linux·服务器