Git Clean | Atlassian Git Tutorial (2024)

To better demonstrate the difference between tracked and untracked files consider the following command line example

$mkdirgit_clean_test
$cdgit_clean_test/
$gitinit.
InitializedemptyGitrepositoryin/Users/kev/code/git_clean_test/.git/
$echo"tracked">./tracked_file
$gitadd./tracked_file
$echo"untracked">./untracked_file
$mkdir./untracked_dir&&touch./untracked_dir/file
$gitstatus
Onbranchmaster

Initialcommit

Changestobecommitted:(use"gitrm--cached<file>..."tounstage)

newfile:tracked_file

Untrackedfiles:(use"gitadd<file>..."toincludeinwhatwillbecommitted)untracked_dir/untracked_file

Git Clean | Atlassian Git Tutorial (1)

related material

Git cheat sheet

Check it out

Git Clean | Atlassian Git Tutorial (2)

SEE SOLUTION

Learn Git with Bitbucket Cloud

Read tutorial

The example creates a new Git repository in the git_clean_test directory. It then proceeds to create a tracked_file which is added to the Git index, additionally, an untracked_file is created, and an untracked_dir. The example then invokes git status which displays output indicating Git's internal state of tracked and untracked changes. With the repository in this state, we can execute the git clean command to demonstrate its intended purpose.

$gitcleanfatal:clean.requireForcedefaultstotrueandneither-i,-n,nor-fgiven;refusingtoclean

At this point, executing the default git clean command may produce a fatal error. The example above demonstrates what this may look like. By default, Git is globally configured to require that git clean be passed a "force" option to initiate. This is an important safety mechanism. When finally executed git clean is not undo-able. When fully executed, git clean will make a hard filesystem deletion, similar to executing the command line rm utility. Make sure you really want to delete the untracked files before you run it.

Common options and usage

Given the previous explanation of the default git clean behaviors and caveats, the following content demonstrates various git clean use cases and the accompanying command line options required for their operation.

-n

The -n option will perform a “dry run” of git clean. This will show you which files are going to be removed without actually removing them. It is a best practice to always first perform a dry run of git clean. We can demonstrate this option in the demo repo we created earlier.

$gitclean-n
Wouldremoveuntracked_file

The output tells us that untracked_file will be removed when the git clean command is executed. Notice that the untracked_dir is not reported in the output here. By default git clean will not operate recursively on directories. This is another safety mechanism to prevent accidental permanent deletion.

-for--force

The force option initiates the actual deletion of untracked files from the current directory. Force is required unless the clean.requireForce configuration option is set to false. This will not remove untracked folders or files specified by .gitignore. Let us now execute a live git clean in our example repo.

$gitclean-f
Removinguntracked_file

The command will output the files that are removed. You can see here that untracked_file has been removed. Executing git status at this point or doing a ls will show that untracked_file has been deleted and is nowhere to be found. By default git clean -f will operate on all the current directory untracked files. Additionally, a < path > value can be passed with the -f option that will remove a specific file.

gitclean-f<path>
-dincludedirectories

The -d option tells git clean that you also want to remove any untracked directories, by default it will ignore directories. We can add the -d option to our previous examples:

$gitclean-dn
Wouldremoveuntracked_dir/
$gitclean-df
Removinguntracked_dir/

Here we have executed a 'dry run' using the -dn combination which outputs untracked_dir is up for removal. Then we execute a forced clean, and receive output that untracked_dir is removed.

-xforceremovalofignoredfiles

A common software release pattern is to have a build or distribution directory that is not committed to the repositories tracking index. The build directory will contain ephemeral build artifacts that are generated from the committed source code. This build directory is usually added to the repositories .gitignore file. It can be convenient to also clean this directory with other untracked files. The -x option tells git clean to also include any ignored files. As with previous git clean invocations, it is a best practice to execute a 'dry run' first, before the final deletion. The -x option will act on all ignored files, not just project build specific ones. This could be unintended things like ./.idea IDE configuration files.

gitclean-xf

Like the -d option -x can be passed and composed with other options. This example demonstrates a combination with -f that will remove untracked files from the current directory as well as any files that Git usually ignores.

Interactive mode or git clean interactive

In addition to the ad-hoc command line execution we have demonstrated so far, git clean has an "interactive" mode that you can initiate by passing the -i option. Let us revisit the example repo from the introduction of this document. In that initial state, we will start an interactive clean session.

$gitclean-di
Wouldremovethefollowingitems:
untracked_dir/untracked_file
***Commands***
1:clean2:filterbypattern3:selectbynumbers4:askeach5:quit6:help
Whatnow>

We have initiated the interactive session with the -d option so it will also act upon our untracked_dir. The interactive mode will display a What now> prompt that requests a command to apply to the untracked files. The commands themselves are fairly self explanatory. We'll take a brief look at each in a random order starting with command 6: help. Selecting command 6 will further explain the other commands:

Whatnow>6
clean-startcleaning
filterbypattern-excludeitemsfromdeletion
selectbynumbers-selectitemstobedeletedbynumbers
askeach-confirmeachdeletion(like"rm-i")
quit-stopcleaning
help-thisscreen
?-helpforpromptselection
5:quit

Is straight forward and will exit the interactive session.

1:clean

Will delete the indicated items. If we were to execute 1: cleanat this point untracked_dir/ untracked_filewould be removed

4:askeach

will iterate over each untracked file and display a Y/Nprompt for a deletion. It looks like the following:

***Commands***
1:clean2:filterbypattern3:selectbynumbers4:askeach5:quit6:help
Whatnow>4
Removeuntracked_dir/[y/N]?N
Removeuntracked_file[y/N]?N
2:filterbypattern

Will display an additional prompt that takes input used to filter the list of untracked files.

Wouldremovethefollowingitems:
untracked_dir/untracked_file
***Commands***
1:clean2:filterbypattern3:selectbynumbers4:askeach5:quit6:help
Whatnow>2
untracked_dir/untracked_file
Inputignorepatterns>>*_file
untracked_dir/

Here we input the *_file wildcard pattern which then restricts the untracked file list to just untracked_dir.

3:selectbynumbers

Similar to command 2, command 3 works to refine the list of untracked file names. The interactive session will prompt for numbers that correspond to an untracked file name.

Wouldremovethefollowingitems:
untracked_dir/untracked_file
***Commands***
1:clean2:filterbypattern3:selectbynumbers4:askeach5:quit6:help
Whatnow>3
1:untracked_dir/2:untracked_file
Selectitemstodelete>>2
1:untracked_dir/*2:untracked_file
Selectitemstodelete>>
Wouldremovethefollowingitem:
untracked_file
***Commands***
1:clean2:filterbypattern3:selectbynumbers4:askeach5:quit6:help

Summary

To recap, git clean is a convenience method for deleting untracked files in a repo's working directory. Untracked files are those that are in the repo's directory but have not yet been added to the repo's index with git add. Overall the effect of git clean can be accomplished using git status and the operating systems native deletion tools. Git clean can be used alongside git reset to fully undo any additions and commits in a repository.

Share this article

Next Topic
Git revert
Git Clean | Atlassian Git Tutorial (2024)

FAQs

How do I completely clean a git repository? ›

Steps to delete untracked Git files
  1. Run git clean -n to see a dry run.
  2. Run git clean -f to force untracked file deletion.
  3. Use git clean -f -d to remove untracked directories.
  4. Use git clean -f -x to remove untracked . gitignore files.
  5. Add the -i switch to do an interactive git clean.
Sep 1, 2023

What is the difference between git reset and git clean? ›

After discussing git clean command, which clears working area by deleting untracked files, Nina reviews git reset command, which removes the file from the index while keeping it in the working directory.

Is it possible to undo a git clean? ›

When finally executed git clean is not undo-able. When fully executed, git clean will make a hard filesystem deletion, similar to executing the command line rm utility. Make sure you really want to delete the untracked files before you run it.

Does git clean remove ignored files? ›

DESCRIPTION. Cleans the working tree by recursively removing files that are not under version control, starting from the current directory. Normally, only files unknown to Git are removed, but if the -x option is specified, ignored files are also removed.

How do I delete all traces of git? ›

The filter-branch command effectively finds all commits that include the file to remove, then removes the file. The prepartory three commands (rm, commit, push) may not be necessary. After this process all traces of the contents of test/private.py are removed from the repository.

How do I cleanse my git? ›

The following natural colon cleanses can be done cheaply, and they're also quite safe if done correctly.
  1. Hydration. Drinking plenty of water and staying hydrated is a great way to regulate digestion. ...
  2. Saltwater flush. ...
  3. High fiber diet. ...
  4. Juices and smoothies. ...
  5. Juice fast. ...
  6. More resistant starches. ...
  7. Probiotics. ...
  8. Herbal teas.

Does git clean remove local commits? ›

Doing a git revert makes new commits to remove old commits in a way that keeps everyone's history sane. git reset --hard <commit hash, branch, or tag> if you want to go to a specific reference other than a remote branch. This will not only discard local commits, but also throw away everything in your work tree (ie.

How do I restore all files in git? ›

git restore #

This command restores files and directories deleted from the staging area or the working tree. Note that it only works for tracked files, meaning that any files that weren't git add -ed to the working tree are excluded. Another option is to restore all of the files in the current directory: git restore .

How do you completely remove files from git? ›

The git rm command can be used to remove individual files or a collection of files. The primary function of git rm is to remove tracked files from the Git index. Additionally, git rm can be used to remove files from both the staging index and the working directory.

What does git clean do? ›

DESCRIPTION. Cleans the working tree by recursively removing files that are not under version control, starting from the current directory. Normally, only files unknown to Git are removed, but if the -x option is specified, ignored files are also removed. This can, for example, be useful to remove all build products.

Which files should be ignored in git? ›

Ignored files are usually build artifacts and machine generated files that can be derived from your repository source or should otherwise not be committed. Some common examples are: dependency caches, such as the contents of /node_modules or /packages. compiled code, such as .o , .pyc , and .class files.

Does git delete empty folders? ›

Git will refuse to delete directories with . git sub directory or file unless a second -f is given. Show what would be done and clean files interactively.

How to reset git repo completely? ›

Takeaways
  1. Only do a hard reset if you are the only using the remote repository, or if you haven't yet pushed the commits you're going to drop.
  2. Find the commit hash of the commit you want to reset to with git log .
  3. Perform the local hard reset by running git reset --hard <commit-hash> .
Jun 21, 2020

How do I clean up my GitHub repository? ›

Deleting a repository
  1. On GitHub, navigate to the main page of the repository.
  2. Under your repository name, click Settings. ...
  3. On the "General" settings page (which is selected by default), scroll down to the "Danger Zone" section and click Delete this repository.
  4. Click I want to delete this repository.

How do I completely delete a git repository? ›

Open Git GUI and select the repository. Go to the Repository menu. Choose Delete Repository .

How do I remove all changes from git? ›

Try Git checkout --<file> to discard uncommitted changes to a file. Git reset --hard is for when you want to discard all uncommitted changes. Use Git reset --hard <commit id> to point the repo to a previous commit.

Top Articles
Diffie-Hellman, RSA, DSA, ECC and ECDSA - Asymmetric Key Algorithms
Do more people use Waze, Apple Maps or Google Maps?
Here’s how much Tim Ballard made during final months with Operation Underground Railroad
fir1 - Window-based FIR filter design
Hannah Slomowitz
Kian And Jc Seatgeek Promo Code
Skip The Games Maui
Kiddle Encyclopedia
124 Indian Pointe, Unit 124, Osage Beach, MO 65065 | Compass
Craigslist Parker Az
Pizza & Pasta Paradies Pizzaservice, Räcknitzhöhe 35a in 01217 Dresden
Wells County Beacon Gis
Tsymo Pet Feeder Manual Pdf
David Bromstad Salary Per Episode
Today Was A Good Day With Lyrics
Graveler Gen 3 Learnset
Las Vegas Noaa
Max Verstappen: Red Bull driver isn't even 'feisty' claims Jacques Villeneuve ahead of Singapore GP
Van der Poel kleurt EK op kasseien, maar Merlier wint sprint vlak voor Kooij
Dinar Guru Detective
Best Pizza In Westlake
Forsyth County, GA population by year, race, & more
Honeywell V8043E1012 Wiring Diagram
Nashville Predators Wiki
Events • Constellation
Pawn Shop Moline Il
Apple Store Near Me Make Appointment
Strange World Showtimes Near Harkins Theatres Christown 14
Lockstraps Net Worth
SpeechWire Tournament Services
Find A Red Cross Blood Drive
Barbie Showtimes Near Cmx Hollywood 16 & Imax
Craigslist Red Wing Mn
Noaa Weather Seward
Doublelist Lima
Santa Cruz Craigslist Cars And Trucks - By Owner
The Exorcist: Believer Showtimes Near Regal Jack London
Maps Michigan Login
Savannah Riddle Marshall Tx
Roane County Arrests Today
80 For Brady Showtimes Near Regal Largo Mall
Lone Star Funds | LinkedIn
Der frühere Jenaer Prorektor Otto Stamfort im Porträt
Lorraine Oakley Upcoming Sales
Berks County Court Schedule
Hashtag Basketball Defense Vs Position
Ucsd Financial Aid Appeal
Premier League live: FT: Liverpool 5-0 Watford
Coors Field Seats In The Shade
1By1 Roof
Funbox Lone Tree Tickets
Latest Posts
Article information

Author: Merrill Bechtelar CPA

Last Updated:

Views: 5906

Rating: 5 / 5 (70 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Merrill Bechtelar CPA

Birthday: 1996-05-19

Address: Apt. 114 873 White Lodge, Libbyfurt, CA 93006

Phone: +5983010455207

Job: Legacy Representative

Hobby: Blacksmithing, Urban exploration, Sudoku, Slacklining, Creative writing, Community, Letterboxing

Introduction: My name is Merrill Bechtelar CPA, I am a clean, agreeable, glorious, magnificent, witty, enchanting, comfortable person who loves writing and wants to share my knowledge and understanding with you.