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.comgit@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
相关推荐
嘻嘻仙人16 小时前
Ubuntu中 git上传自己的项目和二次上传一般流程
git·github
Patrick_Wilson17 小时前
Squash Merge 的血缘陷阱:为什么删掉的代码又活了过来
前端·git·程序员
沉浸学习的匿名网友19 小时前
什么是 .gitignore?为什么每个 Git 项目几乎都离不开它?
前端·git
深海鱼在掘金2 天前
Git 完全指南 —— 第3章:理解工作区、暂存区、版本库三个核心
git
江华森2 天前
Git 基础筑基:从原理到团队协作的全栈实战
git
JakeJiang2 天前
Git 必备命令指南:从日常高频到项目开发实战
git
叫我少年3 天前
Windows 中安装 git
git
深海鱼在掘金8 天前
Git 完全指南 —— 第1章:Git 概览与版本控制演进
git
noravinsc9 天前
关于Git Flow
git
蜜獾云9 天前
在Git中配置用户名和密码
git