git clean and untracked files
- Version
- 2.51
- Review
- Draft
Summary#
git clean deletes untracked files starting from the current directory. Preview the exact scope with -n first. Use -f to perform the deletion only after checking that list. Files that have never been stored in Git cannot be recovered from it.
Syntax#
git clean -n -- build/
git clean -f -- build/
git clean -nd
git clean -nx -- build/
git clean -nX -- build/report.cache
Example#
(
set -eu
scratch=$(mktemp -d "${TMPDIR:-/tmp}/devlookup-git.XXXXXX")
trap 'rm -rf -- "$scratch"' EXIT
unset GIT_CONFIG_GLOBAL $(git rev-parse --local-env-vars)
export GIT_CONFIG_NOSYSTEM=1 GIT_TEMPLATE_DIR= LC_ALL=C
export HOME="$scratch" XDG_CONFIG_HOME="$scratch" GIT_ATTR_NOSYSTEM=1
mkdir "$scratch/work"
cd "$scratch/work"
git init -q -b trunk
git config core.excludesFile /dev/null
printf '*.cache\n' > .gitignore
git add -- .gitignore
mkdir build
touch build/report.tmp build/report.cache notes.tmp
git clean -n -- build/
git clean -nx -- build/
git clean -nX -- build/report.cache
git clean -f -- build/
test ! -e build/report.tmp
test -f build/report.cache
test -f notes.tmp
git status --short --ignored -- build/ notes.tmp
)
Expected output#
Would remove build/report.tmp
Would remove build/
Would remove build/report.cache
Removing build/report.tmp
?? notes.tmp
!! build/
Common mistakes#
Without a pathspec, add -d to include untracked directories. A pathspec already includes matching untracked directories. Lowercase -x adds ignored files to the deletion set and uppercase -X selects only ignored files. Preview again whenever you change the flags or paths. A second -f can remove nested untracked Git repositories.
Version applicability#
Git 1.3 documented -n, -d, -x and -X. Git 1.5.2 added -f. The Git 2.24 manual documents cleanup scoped to a directory without -d. Use explicit file paths with -X on older Git versions. Git 2.28 can miss ignored files under a matched directory, and Git 2.32 fixed ignored-path traversal. The complete example requires Git 2.28 or later for git init -b.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0