借着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 的解释
# 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 如下是脚本全文:
#!/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
840

被折叠的 条评论
为什么被折叠?



