git一键push的脚本

借着ai帮助写了以下脚本,希望能运行当前脚本后,直接完成add/commit/push 3条命令,

适用于频繁需要git push的情形,

如果写得有错误,请各位大佬指正,

1,使用的ssh模式进行push,https有的时候连不上git

2,需要提前添加本机ssh key到GitHub仓库

3,"# Check write permission" 是检查是否具有写权限,如果你的账户在当前目录又写权限,这一段可以删除

4,可以在运行此脚本时,后面添加git commit内容,如果直接运行脚本(即脚本后不加任何内容),则commit内容是当前时间戳

5,xxx/yyy.git 的解释

bash 复制代码
# Ensure remote is SSHsudo git remote set-url origin [url=mailto:git@github.com]git@github.com[/url]:xxx/yyy.git
echo "Using SSH remote..."

这一段的"[url=mailto:git@github.com]git@github.com[/url]:xxx/yyy.git"内容,是你需要push的仓库,xxx是GitHub用户名,yyy是仓库名

6 如下是脚本全文:

bash 复制代码
#!/bin/bash
#Git auto commit & push (SSH) with write permission check
REPO_DIR=$(pwd)
GIT_DIR="$REPO_DIR/.git"

# Check write permission
if [ ! -w "$GIT_DIR" ]; then
    echo "Error: You do not have write permission for the Git repository."
    echo "Run: sudo chown -R $(whoami) $REPO_DIR"
    exit 1
fi

# Check for changes (including untracked files)
#if sudo git diff --cached --quiet && sudo git diff --quiet; then
if [ -z "$(sudo git status --porcelain)" ]; then
    echo "No changes detected, skipping commit."
else
    if [ $# -eq 0 ]; then
        msg="Auto commit on $(date +%Y-%m-%d %H:%M:%S)"
    else
        msg="$*"
    fi
    echo "Adding changes..."
    sudo git add .
    echo "Committing changes..."
    sudo git commit -m "$msg"
fi

# Get current branch
branch=$(sudo git rev-parse --abbrev-ref HEAD)
echo "Current branch: $branch"

# Ensure remote is SSH
sudo git remote set-url origin [url=mailto:git@github.com]git@github.com[/url]:xxx/yyy.git
echo "Using SSH remote..."

# Test SSH connection
ssh -T [url=mailto:git@github.com]git@github.com[/url] 2>&1 | grep -q "successfully authenticated"
if [ $? -ne 0 ]; then
    echo "SSH not working. Check your SSH key."
    exit 1
fi

# Push
sudo git push origin "$branch"

if [ $? -eq 0 ]; then
    echo "Push successful!"
else
    echo "Push failed. Check SSH key or network."
fi
相关推荐
vibecoding日记1 天前
为什么我就想要「线性历史 + Signed Commits」,GitHub 却把我当猴耍 🤬🎙️
git·编程工具
程序员小崔日记1 天前
如何将代码轻松上传到 Gitee?Git 使用全攻略!
git·gitee·上传
Bigger2 天前
为什么你的 Git 提交需要签名?—— Git Commit Signing 完全指南
git·开源·github
DianSan_ERP3 天前
电商API接口全链路监控:构建坚不可摧的线上运维防线
大数据·运维·网络·人工智能·git·servlet
红豆子不相思3 天前
Tomcat 环境搭建与集群实战
服务器·git·tomcat
杰哥技术分享3 天前
Git 仓库迁移技术文档:从 CODING.net 迁移至腾讯云 CNB
git
梅孔立3 天前
Ansible 100 台服务器一键管控实战 进阶版
服务器·git·ansible
qq_426003964 天前
git切换当前分支到远程分支
git
ON10N4 天前
100% 纯 Vibe Coding,我是怎么用 AI 撸出一个 VS Code 插件的
git·ai编程·visual studio code