clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

Git: all about adding files to the staging area

Filed under: Source code management— Tagged with: git

Tricks and tips on adding files to staging area in Git. Using globs and limiting the scope of add, etc.

Adding files in git. The following quote is grabbed from the Git documentation:

Git has three main states that your files can reside in: committed, modified, and staged. Committed means that the data is safely stored in your local database. Modified means that you have changed the file but have not committed it to your database yet. Staged means that you have marked a modified file in its current version to go into your next commit snapshot.

The staging area is pretty cool thing, and unique only to Git. The act of adding, means adding to the staging area.

The basics of adding files to the staging area

# Add a single file
$ git add <file>

# It can be a path also
$ git add path/to/a/<file>

Add all the changed files from all sub directories:

$ git add .

If you’re in the project root, the previous command will add everything from all the directories. If you’re in, say, projectroot/js it’ll only affect the files in the js directory. This comes really handy when there are tons of new files to add in a given directory.

Adding deleted files

When git add . is issued, deleted files won’t be added to the commit (or the deletion of the file is not added to the commit). You can use the -u flag, short for --update, to do that.

From kernel.org (emphasis mine):

[...] That means that it will never stage new files, but that it will stage modified new contents of tracked files and that it will remove files from the index if the corresponding files in the working tree have been removed.

This will add all deleted files:

$ git add -u

The previous command affects the whole working tree, all files in all folders are added, despite the current working directory.

The scope of this command can be limited by navigating to the wanted directory, and issue the following command, note the dot:

$ cd foo/
$ git add -u .

If you want to do add . and add -u in the same command, you might go:

$ git add -u . && git add -u

But there’s a built way to do that: -A short for --all.

$ git add -A

Interesting thread on this.

Using Globs

Globbing is possible when adding files. Globs are a bit like regex, but easier to understand and more limited.

The below code adds all files ending with .js in the javascript directory:

$ git add javascript/*.js

Or add all possible files in plugins dir:

$ git add plugins/*

You get the point.

Also, see my post on removing files in Git.

Comments would go here, but the commenting system isn’t ready yet, sorry.

  • © 2022 Antti Hiljá
  • About
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!