git仓库基本使用
本文介绍了本地仓库和远程仓库的快速连接,下拉和上传代码。下面是用 SSH 公钥建立 Git 连接的一整套步骤(含 Windows/PowerShell 与 Git Bash 常用命令),按顺序做就行。
1) 检查是否已有密钥
# Git Bash / macOS / Linux
ls -l ~/.ssh# Windows PowerShell
Get-ChildItem $env:USERPROFILE\.ssh
看到 id_ed25519/id_ed25519.pub 就说明已有密钥(可跳到步骤 3)。
2) 生成密钥(推荐 ed25519)
Git Bash / macOS / Linux:
ssh-keygen -t ed25519 -C "你的邮箱@example.com"
# 一路回车;可选设置 passphrase 保护私钥
Windows PowerShell:
ssh-keygen -t ed25519 -C "你的邮箱@example.com" -f $env:USERPROFILE\.ssh\id_ed25519
生成后会得到:
私钥:~/.ssh/id_ed25519(不要外传)
公钥:~/.ssh/id_ed25519.pub(可上传到代码托管平台)
3) 启动 ssh-agent 并加载私钥(免每次输入)
Windows PowerShell(系统自带 OpenSSH):
# 开机自启 & 立即启动
Get-Service ssh-agent | Set-Service -StartupType Automatic
Start-Service ssh-agent
ssh-add $env:USERPROFILE\.ssh\id_ed25519
Git Bash / macOS / Linux:
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
4) 复制“公钥”并添加到代码平台
查看并复制:
# Git Bash / macOS / Linux
cat ~/.ssh/id_ed25519.pub# Windows PowerShell(直接进剪贴板)
Get-Content $env:USERPROFILE\.ssh\id_ed25519.pub | Set-Clipboard
到你的 Git 服务器(GitHub/GitLab/Gitea/公司私服)→ 个人设置 SSH Keys → Add new key → 粘贴保存。
5) (你有自定义端口 1024)写 SSH 配置更省事
编辑 ~/.ssh/config(没有就新建),加入:
Host wpsitHostName git.wpsit.cnUser gitPort 1024IdentityFile ~/.ssh/id_ed25519IdentitiesOnly yes
以后就能用简写
wpsit:owner/repo.git当远程地址了。
6) 测试 SSH 连接
# 直接写主机和端口
ssh -T git@git.wpsit.cn -p 1024
# 或者用上一步的别名
ssh -T wpsit
首次会问 Are you sure you want to continue connecting (yes/no)? 输入 yes。
成功会看到欢迎/鉴权成功提示。
【注】只完成1,2,4步就可以完成基本的连接,此时可以使用下述指令测试:
Git Bash / macOS / Linux:
ssh -T -p 1024 -i ~/.ssh/id_ed25519 git@git.wpsit.cn
Windows PowerShell:
ssh -T -p 1024 -i "$env:USERPROFILE\.ssh\id_ed25519" git@git.wpsit.cn
说明:
-T 不分配终端(Git 服务器常用),成功会回显类似 “successfully authenticated / welcome …(但禁止 shell)”。第一次会提示 Are you sure you want to continue connecting (yes/no)?,输入 yes。
7) 绑定/切换 Git 远程地址
新增远程:
# 用 Host 别名(推荐)
git remote add origin wpsit:hust-2027-fullstack-tasks/chenqiling.git# 或者显式 URL(含端口)
git remote add origin ssh://git@git.wpsit.cn:1024/hust-2027-fullstack-tasks/chenqiling.git
切换已存在的远程:
git remote set-url origin wpsit:hust-2027-fullstack-tasks/chenqiling.git
# 或者
git remote set-url origin ssh://git@git.wpsit.cn:1024/hust-2027-fullstack-tasks/chenqiling.git
确认:
git remote -v
8) 下拉与上传(验证公钥是否生效)
克隆(下拉):
git clone wpsit:hust-2027-fullstack-tasks/chenqiling.git
# 或 ssh://git@git.wpsit.cn:1024/hust-2027-fullstack-tasks/chenqiling.git
已有仓库首次推送:
git add .
git commit -m "init"
git push -u origin master # 或 main,按你的分支名
常见故障快查
-
Permission denied (publickey)- 公钥没加到平台;2)
ssh-add -l看看私钥是否已加入 agent; ~/.ssh/config是否指向对的IdentityFile;- 端口 1024 是否放行;
- 逐条排查:
ssh -vvv -T git@git.wpsit.cn -p 1024
- 公钥没加到平台;2)
-
Windows 权限问题(罕见):在 Git Bash 执行
chmod 700 ~/.ssh chmod 600 ~/.ssh/id_ed25519 chmod 644 ~/.ssh/id_ed25519.pub
快速使用:
# 新功能
git switch -c feature/xxx
# ...开发...
git add .
git commit -m "feat(xxx): 完成初版"
git pull --rebase
git push -u origin feature/xxx
# 提 PR / 合并后
git switch main
git pull --rebase
git branch -d feature/xxx
