一、基本配置
git config --globaluser.name "你自己的用户名"
git config --globaluser.email "你自己的邮箱"
ssh-keygen -t rsa -C"你自己的邮箱"
生成后的公匙文件在 C:Users用户名.sshid_rsa.pub,打开密匙文件并复制其中内容将该密匙添加到github (Account Settings-> SSH key-> Add SSHkey )
确保新项目使用 main
作为默认分支
在本地配置中将新项目的初始化默认分支设置为 main
:
git config --global init.defaultBranch main
这样,git init
时会自动创建 main
作为默认分支。
安装Git,初始化本地 Git 仓库,创建一个新的 Git 仓库
二、提交与拉取
将工作目录中的所有更改(新文件、修改文件)添加到暂存区。
git commit -m "first commit"
提交暂存区中的所有文件到本地仓库,提交信息为 "first commit"。
git remote add origin git@github.com:peiyafei/HrClient.git
关联远程仓库,将本地仓库与 GitHub 仓库(HrClient
)关联。
git branch -m master main
这会将本地的 master
分支重命名为 main
git add .
git commit -m "add new changes"
添加新的修改到暂存区,并提交到本地仓库。
git push origin main --force
三、高级操作
HEAD
代表当前分支的最新提交(上次拉取后你已经同步的提交)。
该命令会丢弃所有本地的更改(包括工作区和暂存区的修改),将文件恢复为上次提交的状态。
同步远程仓库: 如果你还想确保本地分支与远程仓库一致,可以运行:
git pull origin <branch-name>
四、脚本制作
git_auto_commit.sh
脚本放在 Git 仓库的根目录下,每次进入该仓库时,可以直接在 Git Bash 中运行它。
脚本内容:
#!/bin/bash
# 确保 build 文件夹被忽略
if ! grep -q "^build$" .gitignore; then
echo "build" >> .gitignore
echo "Added 'build' to .gitignore"
fi
# 使用固定的提交信息
commit_message="修复了一些已知问题"
移除 Git 缓存中的所有文
git rm -r --cached .
# 添加所有更改到暂存区(忽略被 .gitignore 忽略的文件)
git add .
# 提交更改
git commit -m "$commit_message"
# 推送更改到远程仓库
git push origin main
# 显示当前分支状态
git status
升级版脚本:
#!/bin/bash
# =============================================================
# 文件名:git_auto_commit.sh
# 说明:自动提交脚本
# 作者:peiyafei
# 创建日期:2025-01-03 00:27:27
# =============================================================
# 设置 Git 换行符配置
git config core.autocrlf true
# 创建 .gitattributes(如果不存在)
if [ ! -f .gitattributes ]; then
cat > .gitattributes << EOF
* text=auto
*.sh text eol=lf
*.gitignore text eol=lf
*.cpp text eol=lf
*.h text eol=lf
*.qml text eol=lf
*.txt text eol=lf
*.md text eol=lf
EOF
echo "Created .gitattributes file"
fi
# 检查并创建 .gitignore
if [ ! -f .gitignore ]; then
cat > .gitignore << EOF
# Build directories
build/
debug/
release/
# IDE files
.vscode/
.idea/
*.user
*.pro.user
CMakeLists.txt.user
# Generated files
*.o
*.obj
moc_*
qrc_*
ui_*
# Temporary files
*~
*.autosave
EOF
echo "Created .gitignore file"
elif ! grep -q "^build/$" .gitignore; then
echo "build/" >> .gitignore
echo "Added 'build/' to .gitignore"
fi
# 添加所有更改到暂存区
git add .
# 提交更改
git commit -m "修复了一些已知问题"
# 推送到远程仓库
git push origin main
# 显示状态
git status
echo "============================================================="
echo "Commit completed at: $(date '+%Y-%m-%d %H:%M:%S')"
echo "By user: $(git config user.name)"
echo "============================================================="
chmod +x git_auto_commit.sh
每次修改完代码后,在 Git Bash 中运行该脚本:
脚本会自动执行 git add .
、git commit
和 git push
命令,将更改提交并推送到远程仓库。