Understanding GIT on the Mac
Struggling with Git, I decided to return to first principles and do everything in the terminal. I had been using either a GUI or Visual Studio Code, but I didn’t really understand what was happening in the background. Here are my notes for future me—and for you, if you’ve stumbled upon this.
tl/dr
As a quick start, this is what I need to do if I have an empty repository in Github and a folder of files locally that I want to sync.
git init -b main
git add .
git commit -m "message"
git remote add origin https://github.com/your-username/your-repo.git
git push -u origin main
Might need this if this error is returned ‘fatal: the remote end hung up unexpectedly’:
git config --global http.postBuffer 524288000
Setup
GIT gets installed with Xcode command line tools, otherwise it can be installed with Homebrew.
git version
brew install git
Working locally
Folder with existing files
A new folder can be initialised using git init
. This creates a hidden subfolder (.git). See this for an explanation of what’s included in this folder.
The Mac appears to default to calling the branch name “master” and Github used “main”. This can cause complications when syncing. To avoid this ensure the local branch is called ‘main’.
When initialising use:
git init -b main
If you forget, change the branch name via: `git checkout old-name git branch -m new-name git branch -a
All existing files in the folder are untracked at this time. If the local folder has files to be included, use git add .
. This adds the existing files to the index but nothing is committed yet (there is no snapshot of the files).
Initial commit
To commit changes locally
git commit -m "message"
New (untracked) files
If a file is added to the folder, it is untracked until added to git. The file is added to git by git add <filename>
and becomes tracked.
Syncing to GitHub
To sync an existing local folder to GitHub, create an empty repo on GitHub (no need to initialise with README):
git remote add origin https://github.com/your-username/your-repo.git
git push -f origin main
Note: GIT needs to be configured with a user name and email.
git config --global user.name "Your Name"
git config --global user.email "your-email@example.com"
If it happens that the remote git repo with content is created first, git clone "URL"
will create a copy of the repository on GitHub inside the current folder. It gets messy to merge to two.
- If a remote repo already has content, it’s best to clone it first rather than starting a local folder separately.
- If you already have a local folder with content, instead of cloning, add the remote and pull first:
git remote add origin https://github.com/your-username/your-repo.git
git pull origin main --rebase # Ensures local and remote sync