--- title: Denny 學長的 Git 教學(上) description: Git 是在不論是開源或是工程師在工作中常使用的版本控制工具,用來監督程式碼的開發,也可以變成多人合作的利器。但在大學課堂中,教師並不會教導學生使用,更多的學生甚至都不知道有這樣的工具存在。這堂課將帶領大家認識 Git 的基本概念和常用指令,讓你在未來的開發道路上更加順暢。 tags: - 社課 - 共筆 - 113 學年 --- :::success # Denny 學長的 Git 教學(上) **時間:** 2025/04/24(星期四)18:00~20:00 **地點:** 挺生大樓 A3-200 教室 **簡報:** [連結](https://denny.one/git-slide/) **Slido:** [連結](https://app.sli.do/event/fAMhbRNE6AiDbmnSBijuPf) ::: > 請從這裡開始 課前設置:https://hackmd.io/@ttussc/before-git [toc] ### 準備 - install git -> https://git-scm.com/ `sudo apt install git` - Windows: 請toggle hidden files及file extensions。 ### Useful shell commands `pwd` `mkdir` `cd` `ls` (`-al`) ### Git vs GitHub Git: 版控工具 GitHub : git repository hosting platform ### Git #### Environment setup 設定檔案位置:`~/.gitconfig` - Setup Username & Email ``` git config --global user.email <your-email@example.com> git config --global user.name <your-name> ``` - Setup Default Editor ``` git config --global core.editor <editor> ``` 像是Notepad++ ``` git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -nosession" ``` #### Working Dir, Staging Area, Repository ![image](https://hackmd.io/_uploads/rys5tqD1eg.png) #### Useful Git Commands - `git --help` - `git status` - `git log` 查看commit history `git lg` -> 更漂亮的 `git log` - `git show <commit hash>` - `git rm --cached <file>` untrack file - `git switch <branch/commithash>` switch to that branch `# -c will create the unexisted branch` - `git reflog` ### GitHub #### Create repository 去 https://github.com/<username>?tab=repositories 右邊有個綠色的**New** ### License, README, .gitignore #### License https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/licensing-a-repository #### README.md You can add a README file to your repository to tell other people why your project is useful, what they can do with your project, and how they can use it. #### .gitignore https://docs.github.com/en/get-started/git-basics/ignoring-files 如果你有些file/dir不想被版控 (如build, project settings),可以用。 ### Create Local Git Repository 1. create a file (optional) ex. `echo "# RepositoryName" >> README.md` `Create README.md file` 2. create an empty Git repository `git init` 3. Add an file to index (stage changes) ex. `git add README.md` `# Add README.md file` `git add .` `# Add all files in the Repo to index` 4. Commit the staged changes `git commit -m "<commit message>"` `# -m <message> specifies the commit message` 5. Rename current branch to main `git branch -M main` (-M 會強制把現在的branch rename) 6. Add remote Git repository `git remote add <remote-name> <url>` `git remote set-url <remote-name> <url>` `# 更改URL` ex. `git remote add origin https://github.com/<Username>/<Repository>.git` 7. Push to remote Git repository `git push -u <remote-name> <branch>` `# -u link your local branch to a remote branch` ex. `git push -u origin main`