本文目录导读:

是的,可以通过脚本自动完成代码提交和推送,以下是几种常见实现方式:
基础 Shell 脚本
#!/bin/bash # 设置变量 REPO_DIR="/path/to/your/repo" COMMIT_MESSAGE="Auto commit: $(date)" BRANCH="main" # 进入仓库目录 cd $REPO_DIR || exit 1 # 添加所有更改 git add . # 提交代码 git commit -m "$COMMIT_MESSAGE" # 推送到远程 git push origin $BRANCH
高级脚本(带错误处理)
#!/bin/bash
set -e # 出错立即退出
# 配置
REPO_DIR="/path/to/repo"
BRANCH="main"
REMOTE="origin"
cd $REPO_DIR
# 检查是否有更改
if ! git status --porcelain | grep -q .; then
echo "没有需要提交的更改"
exit 0
fi
echo "检测到更改,开始提交..."
# 拉取最新代码避免冲突
git pull $REMOTE $BRANCH --rebase
# 提交并推送
git add .
git commit -m "自动提交: $(date '+%Y-%m-%d %H:%M:%S')"
git push $REMOTE $BRANCH
echo "提交成功!"
定时自动提交(使用 cron)
Linux/Mac crontab 配置:
# 每天9点执行 0 9 * * * /path/to/auto-commit.sh # 每小时执行 0 * * * * /path/to/auto-commit.sh # 每30分钟执行 */30 * * * * /path/to/auto-commit.sh
Windows 任务计划程序:
- 打开“任务计划程序”
- 创建基本任务
- 设置触发器(如每天/每小时)
- 操作:启动程序 →
git-bash.exe→ 参数:-c "/path/to/auto-commit.sh"
密码/令牌认证
使用 SSH 密钥(推荐):
# 生成 SSH 密钥 ssh-keygen -t rsa -b 4096 -C "your_email@example.com" # 添加到 SSH agent eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_rsa # 将公钥添加到 GitHub/GitLab cat ~/.ssh/id_rsa.pub
使用 Git 凭据存储:
# 缓存密码(默认15分钟) git config --global credential.helper cache # 修改缓存时间(例如1小时) git config --global credential.helper 'cache --timeout=3600' # 永久存储(不推荐,有安全风险) git config --global credential.helper store
使用 Git Hooks
post-commit hook: 提交后自动推送
#!/bin/bash # .git/hooks/post-commit BRANCH=$(git rev-parse --abbrev-ref HEAD) git push origin $BRANCH
GitHub Actions 自动提交
# .github/workflows/auto-commit.yml
name: Auto Commit
on:
schedule:
- cron: '0 */6 * * *' # 每6小时
workflow_dispatch: # 手动触发
jobs:
auto-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Make changes
run: |
echo "Updated at $(date)" >> updates.txt
- name: Commit and Push
run: |
git config user.name github-actions
git config user.email github-actions@github.com
git add .
git commit -m "Auto update: $(date)" || exit 0
git push
注意事项
- 安全风险:不要在脚本中直接写入密码
- 冲突处理:推送前先拉取最新代码
- Git 配置:确保有全局 user.name 和 user.email
- 测试环境:先在测试仓库试运行
- 日志记录:添加日志便于排查问题
# 添加日志记录 LOGFILE="/var/log/auto-commit.log" echo "$(date) - 开始提交" >> $LOGFILE # ... 命令 ... echo "$(date) - 提交完成" >> $LOGFILE
推荐使用 SSH 密钥认证加定时任务的方式,既安全又可靠。