Connect a Local Folder to a GitHub Repository and Ignore Specific Folders

1 Introduction

This blog post introduce how to connect local files to GitHub and selectively sync specific folders, like your coding work, while excluding others (e.g., data folders). You can achieve this by using a .gitignore file to tell Git what to exclude when pushing changes to your GitHub repository.

2 Connect a Local Folder to a Github Repository

  1. Create a repository on Github

    • GitHub provides instructions to help you set up your repository.

  2. Open terminal in the working folder and run commands as instructed

    1
    2
    3
    4
    5
    6
    7
    echo "# Repository" >> README.md
    git init
    git add README.md
    git commit -m "first commit"
    git branch -M main
    git remote add origin https://github.com/tehya-tan/Repository.git
    git push -u origin main

  • Now, this folder is connected to the Git repository on the account.

3 Ignore Folder for Git Repositories

  1. Create or open the .gitignore file: If you don't already have a .gitignore file in your project's root directory, create one. You can use any text editor or run the following command to create this file.

    1
    touch .gitignore

  2. Add folder names to .gitignore and save: Open the .gitignore file and add the names of the folders you want to ignore, each on a separate line.

    For example, if you want to ignore two folders named folder1 and folder2, add the following lines to .gitignore:

    1
    2
    folder1/
    folder2/

    You can continue adding more folder names, each on a new line.

  3. Commit the .gitignore file:

    1
    2
    git add .gitignore
    git commit -m "Added folders to .gitignore"

    Note: The .gitignore file itself needs to be committed to make the ignore rules effective.

4 Push all changes except the ignored folders

  1. Enter git add --all to add all the files or changes to the repository.
  2. Enter git status to see the changes to be committed.
  3. Enter git commit -m '<commit_message>' at the command line to commit new files/changes to the local repository.
  4. Use git push to publish your local commits

We also can push changes only on specific folder and files by replacing the step 1 by

1
git add folder

5 Reference

https://docs.github.com/en/migrations/importing-source-code/using-the-command-line-to-import-source-code/adding-locally-hosted-code-to-github