Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Linux 虛擬機上 Git 與 GitHub 完整實戰教程:從安裝到推送

編輯:Linux 系統常見問題解答

1. 註冊 GitHub 賬號

官網 github.com 註冊,驗證郵箱。

2. 安裝 Git 客戶端

# CentOS/RHELyum install git git-gui# Ubuntu/Debianapt update && apt install git# 源碼編譯 (最新版)wget https://mirrors.edge.kernel.org/pub/software/scm/git/git-2.45.0.tar.gz./configure --prefix=/usr/local/git && make && make install

3. 生成 SSH 密鑰對並上傳公鑰

ssh-keygen -t ed25519 -C "your_email@example.com"  # 推薦 ed25519# 連續回車 (無密碼) 或設置密碼短語cat ~/.ssh/id_ed25519.pub  # 複製內容

GitHub → Settings → SSH and GPG keys → New SSH key → 粘貼公鑰。

4. 測試連接

ssh -T git@github.com# Hi username! You've successfully authenticated...

5. 全局用戶配置

git config --global user.name "Your Real Name"git config --global user.email "your_email@example.com"git config --global init.defaultBranch main  # Git 2.28+git config --global core.editor vim

6. 創建本地倉庫並關聯遠程

mkdir my-project && cd my-projectgit init                    # 初始化 .gitgit add .                  # 暫存所有文件git commit -m "Initial commit"# 在 GitHub 網頁創建同名倉庫 (不勾選 README/License)git remote add origin git@github.com:username/my-project.gitgit push -u origin main     # 首次推送並建立追蹤關系

7. 常見錯誤與修復

錯誤原因修復
Permission denied (publickey)SSH 金鑰未上傳/不匹配/agent 未載入ssh-add ~/.ssh/id_ed25519、檢查 ~/.ssh/config Host github.com IdentityFile
403 / fatal: HTTP request failed使用 HTTPS URL 但無 Token/密碼改用 SSH URL:git remote set-url origin git@github.com:user/repo.git
reject non-fast-forward遠程有本地無的提交git pull --rebase origin main 後再 push
LF will be replaced by CRLF換行符警告git config --global core.autocrlf input (Linux/macOS)

8. 日常工作流

git status           # 查看狀態git diff             # 工作區 vs 暫存區git diff --staged    # 暫存區 vs 倉庫git add -p           # 交互式暫存 (塊級)git commit -v        # 編輯器查看 diff 後提交git log --oneline --graph --all  # 圖形化歷史git stash            # 暫存未完成工作git stash pop        # 恢復

9. 進階:多賬號隔離

# ~/.ssh/configHost github.com-work  HostName github.com  User git  IdentityFile ~/.ssh/id_ed25519_workHost github.com-personal  HostName github.com  User git  IdentityFile ~/.ssh/id_ed25519_personal# 使用git remote set-url origin git@github.com-work:company/project.git
Copyright © Windows教程網 All Rights Reserved