This guide will show you how to add new files and directories to a git repository.
Sample Git Repo
The first step is to set up a sample git repo to illustrate the concepts in this tutorial.
Start by creating a directory as shown:
Navigate into the directory:
Next, initialize the directory as a git repo by running the command:
The command above should initialize an empty directory as a git repository.
Git Add Command
You will use the git add command when adding new files and directories to a git repository.
The command allows you to specify single or multiple filenames or directories.
Let us start by creating a new file in our sample_repo as shown:
To add all the files and directories in the repository, run the command:
The command above will add all the added, deleted, or changed files into the git staging areas.
For new files and directories, this means that git now tracks them.
Note that using the git add . command will add the files and directories in your current working directory.
This is useful when you are at the root of your repository.
You can use the -A flag to tell git to add all the files and directories if you are in a nested directory of the repo.
In this case, all the untracked files and directories in the entire working tree are moved to the staging area.
Git Add Directory
To add a specific directory in git, you can use the git add command followed by the directory’s name.
Start by creating a new directory in the sample_repo.
To add the manual alone, run the command:
The command above will only add the specified and ignore other untracked files.
Git Add Specific File
You can also add a specific file and ignore the others. For example, create a new txt file in the new_dir directory of the sample_repo
To add that particular file, run the command:
Git Add files by Extension
Git also allows you to add files that match a specific extension using a wildcard character.
For example, to add all the files ending in .txt, we can do:
Git Add Modified Files Only
You may only want to add the removed or modified files in some cases. In that case, you can use the -u flag as shown:
The command above should add the deleted or modified files in the current working directory.
Conclusion
In this article, we explored various aspects of the git add command. This command allows you to add files and directories to the git staging area. In addition, you can view the state of your git repo before committing using the git status command.