LinuxCommandLibrary

go-clean

Remove object files and cached data

TLDR

Print the remove commands instead of actually removing anything

$ go clean -n
copy

Delete the build cache
$ go clean -cache
copy

Delete all cached test results
$ go clean -testcache
copy

Delete the module cache
$ go clean -modcache
copy

SYNOPSIS

go clean [-cache] [-i] [-modcache] [-n] [-r] [-testcache] [-x] [build patterns]

PARAMETERS

-cache
    Remove the entire build cache (~/.cache/go-build).

-i
    Remove installed archive or binary (like from go install).

-modcache
    Remove the entire module download cache (~/.cache/gomodcache).

-n
    Print commands that would be executed, but do not run them.

-r
    Apply recursively to matching packages and dependencies.

-testcache
    Remove all stored test results.

-x
    Print all commands as they are executed.

DESCRIPTION

The go clean command removes object files and cached files produced by the Go build system from the specified packages and dependencies. Object files typically include .a archive files or platform-specific equivalents like $GOOS_$GOARCH.a. This helps reclaim disk space and ensures a clean rebuild environment.

By default, it targets the current package's directory, but build patterns (like package paths or ./... for recursive) can specify targets. Flags extend functionality: -i also removes installed binaries or archives created by go install; -r recurses through dependencies; -n dry-runs by printing commands without executing; -x prints executed commands for debugging; -testcache clears the test result cache; recent versions add -cache for the build cache and -modcache for the module cache.

Essential for developers managing large projects, it prevents stale artifacts from causing build inconsistencies. Always run in the project root or specify patterns accurately to avoid unintended deletions.

CAVEATS

Does not remove source code or Go modules by default; use cautiously with -r or -modcache to avoid disrupting other projects sharing the cache. Build patterns follow go build semantics.

EXAMPLES

go clean # Clean current package.
go clean -i ./... # Clean and uninstall recursively.
go clean -cache -modcache # Clear all caches.

CACHE LOCATIONS

Build cache: $GOCACHE (default ~/.cache/go-build).
Module cache: $GOMODCACHE (default ~/go/pkg/mod).

HISTORY

Introduced in early Go versions (pre-1.0, 2009); evolved with build system changes. Go 1.10 added build cache (-cache implied). Go 1.21 explicitly added -cache and -modcache flags for better cache management.

SEE ALSO

go build(1), go install(1), go mod(1), rm(1)

Copied to clipboard