Convert Figma logo to code with AI

dundee logogdu

Fast disk usage analyzer with console interface written in Go

3,790
138
3,790
49

Top Related Projects

8,538

A more intuitive version of du in rust

12,655

Disk Usage/Free Utility - a better 'df' alternative

3,931

View disk space usage and delete unwanted data, fast.

Terminal disk space navigator 🔭

2,155

A TUI system monitor written in Rust

Quick Overview

GDU (Go Disk Usage) is a fast disk usage analyzer written in Go. It's designed to be a more user-friendly and feature-rich alternative to the traditional du command, offering a terminal user interface for easy navigation and analysis of disk space usage.

Pros

  • Fast performance, especially on SSDs
  • Interactive terminal user interface with color coding
  • Cross-platform support (Linux, macOS, Windows)
  • Ability to ignore specific directories or devices

Cons

  • Requires terminal access, not suitable for GUI-only environments
  • May consume significant resources on very large file systems
  • Learning curve for users accustomed to traditional du command
  • Limited customization options compared to some GUI disk analyzers

Getting Started

To install GDU on macOS using Homebrew:

brew install gdu

For other platforms, download the appropriate binary from the GitHub releases page or use your system's package manager if available.

To analyze disk usage in the current directory:

gdu

To analyze a specific directory:

gdu /path/to/directory

For more options and usage information:

gdu --help

Competitor Comparisons

8,538

A more intuitive version of du in rust

Pros of dust

  • Written in Rust, potentially offering better performance and memory safety
  • Provides more detailed file information, including file types and permissions
  • Offers a wider range of sorting options for displayed results

Cons of dust

  • May have a steeper learning curve due to more complex command-line options
  • Slower initial development and release cycle compared to gdu

Code comparison

dust:

pub fn get_dir_size(path: &Path) -> Result<u64, Error> {
    let mut total_size = 0;
    for entry in fs::read_dir(path)? {
        let entry = entry?;
        let metadata = entry.metadata()?;
        if metadata.is_dir() {
            total_size += get_dir_size(&entry.path())?;
        } else {
            total_size += metadata.len();
        }
    }
    Ok(total_size)
}

gdu:

func (a *App) GetDirSize(path string) (int64, error) {
    var size int64
    err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        }
        if !info.IsDir() {
            size += info.Size()
        }
        return nil
    })
    return size, err
}

Both implementations aim to calculate directory sizes recursively, but dust uses a custom recursive function, while gdu utilizes the filepath.Walk function from Go's standard library.

12,655

Disk Usage/Free Utility - a better 'df' alternative

Pros of duf

  • More visually appealing output with color-coded bars and icons
  • Supports a wider range of filesystems and storage types
  • Offers more customization options for output formatting

Cons of duf

  • Slower performance, especially for large filesystems
  • Higher memory usage compared to gdu
  • Less focused on interactivity and navigation

Code Comparison

duf:

func (d *Device) Usage() (*UsageInfo, error) {
    stat := syscall.Statfs_t{}
    err := syscall.Statfs(d.Mountpoint, &stat)
    if err != nil {
        return nil, err
    }
    // ... (calculation logic)
}

gdu:

func (d *Dir) GetUsage() int64 {
    var size int64
    for _, f := range d.Files {
        size += f.Usage()
    }
    for _, s := range d.Dirs {
        size += s.GetUsage()
    }
    return size
}

Both projects are disk usage analyzers written in Go, but they have different focuses. duf provides a more visually rich and informative output, while gdu emphasizes speed and interactivity. The code snippets show that duf uses system calls to gather filesystem information, while gdu recursively calculates directory sizes. This reflects their different approaches: duf for overall system view and gdu for detailed directory analysis.

3,931

View disk space usage and delete unwanted data, fast.

Pros of dua-cli

  • Written in Rust, potentially offering better performance and memory safety
  • Provides a terminal user interface (TUI) for interactive exploration of disk usage
  • Offers parallel scanning of directories for faster results on multi-core systems

Cons of dua-cli

  • May have a steeper learning curve due to its more complex interface
  • Lacks some advanced features present in gdu, such as real-time updates during file deletion
  • Could be less intuitive for users accustomed to simpler command-line tools

Code Comparison

dua-cli:

let mut app = App::default();
let mut terminal = Terminal::new(CrosstermBackend::new(stdout()))?;
terminal.clear()?;

gdu:

app := tui.NewApp()
err := app.Run()
if err != nil {
    log.Fatal(err)
}

Both projects use terminal-based user interfaces, but dua-cli's implementation in Rust may offer performance advantages. gdu's Go code appears more concise, potentially indicating easier maintenance. However, the actual performance and usability differences would require more in-depth analysis and benchmarking.

Terminal disk space navigator 🔭

Pros of diskonaut

  • Interactive and visually appealing disk space visualization
  • Allows real-time deletion of files and directories
  • Provides a more intuitive understanding of disk usage patterns

Cons of diskonaut

  • Written in Rust, which may have a steeper learning curve for contributors
  • Limited to disk space analysis and visualization
  • May be slower for initial scans of large directories

Code comparison

diskonaut (Rust):

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args: Vec<String> = env::args().collect();
    let path = Path::new(&args[1]);
    let mut app = App::new(path)?;
    app.run()?;
    Ok(())
}

gdu (Go):

func main() {
    flag.Parse()
    path := "."
    if flag.NArg() > 0 {
        path = flag.Arg(0)
    }
    err := gdu.Run(path)
    if err != nil {
        log.Fatal(err)
    }
}

Both projects aim to analyze disk usage, but gdu focuses on speed and efficiency, while diskonaut prioritizes interactivity and visualization. gdu is written in Go, making it potentially easier for contributors familiar with the language. It also offers a broader range of features, including file sorting and export options. However, diskonaut's interactive interface may be more user-friendly for those who prefer visual representations of disk usage.

2,155

A TUI system monitor written in Rust

Pros of ytop

  • More comprehensive system monitoring, including CPU, memory, disk, and network usage
  • Interactive interface with keyboard shortcuts for navigation and customization
  • Supports multiple color schemes and layouts

Cons of ytop

  • Higher resource usage due to more extensive monitoring features
  • Less focused on disk usage analysis compared to gdu
  • No longer actively maintained (last commit in 2020)

Code Comparison

ytop (Rust):

pub fn draw<B: Backend>(f: &mut Frame<B>, app: &mut App) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(3), Constraint::Min(0)].as_ref())
        .split(f.size());
    draw_header(f, app, chunks[0]);
    draw_body(f, app, chunks[1]);
}

gdu (Go):

func (d *Dir) UpdateStats(ctx context.Context) error {
    var wg sync.WaitGroup
    for _, f := range d.Files {
        wg.Add(1)
        go func(f *File) {
            defer wg.Done()
            f.UpdateStats(ctx)
        }(f)
    }
    wg.Wait()
    return nil
}

The code snippets demonstrate different approaches: ytop focuses on UI rendering, while gdu emphasizes concurrent file system analysis. ytop uses Rust's tui library for drawing, whereas gdu leverages Go's concurrency features for efficient disk usage calculation.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

go DiskUsage()

Gdu

Codecov Go Report Card Maintainability CodeScene Code Health

Pretty fast disk usage analyzer written in Go.

Gdu is intended primarily for SSD disks where it can fully utilize parallel processing. However HDDs work as well, but the performance gain is not so huge.

asciicast

Packaging status

Installation

Head for the releases page and download the binary for your system.

Using curl:

curl -L https://github.com/dundee/gdu/releases/latest/download/gdu_linux_amd64.tgz | tar xz
chmod +x gdu_linux_amd64
mv gdu_linux_amd64 /usr/bin/gdu

See the installation page for other ways how to install Gdu to your system.

Or you can use Gdu directly via Docker:

docker run --rm --init --interactive --tty --privileged --volume /:/mnt/root ghcr.io/dundee/gdu /mnt/root

Usage

  gdu [flags] [directory_to_scan]

Flags:
      --config-file string            Read config from file (default is $HOME/.gdu.yaml)
  -g, --const-gc                      Enable memory garbage collection during analysis with constant level set by GOGC
      --enable-profiling              Enable collection of profiling data and provide it on http://localhost:6060/debug/pprof/
  -L, --follow-symlinks               Follow symlinks for files, i.e. show the size of the file to which symlink points to (symlinks to directories are not followed)
  -h, --help                          help for gdu
  -i, --ignore-dirs strings           Absolute paths to ignore (separated by comma) (default [/proc,/dev,/sys,/run])
  -I, --ignore-dirs-pattern strings   Absolute path patterns to ignore (separated by comma)
  -X, --ignore-from string            Read absolute path patterns to ignore from file
  -f, --input-file string             Import analysis from JSON file
  -l, --log-file string               Path to a logfile (default "/dev/null")
  -m, --max-cores int                 Set max cores that GDU will use. 8 cores available (default 8)
  -c, --no-color                      Do not use colorized output
  -x, --no-cross                      Do not cross filesystem boundaries
      --no-delete                     Do not allow deletions
  -H, --no-hidden                     Ignore hidden directories (beginning with dot)
      --no-mouse                      Do not use mouse
      --no-prefix                     Show sizes as raw numbers without any prefixes (SI or binary) in non-interactive mode
  -p, --no-progress                   Do not show progress in non-interactive mode
  -u, --no-unicode                    Do not use Unicode symbols (for size bar)
  -n, --non-interactive               Do not run in interactive mode
  -o, --output-file string            Export all info into file as JSON
  -r, --read-from-storage             Read analysis data from persistent key-value storage
      --sequential                    Use sequential scanning (intended for rotating HDDs)
  -a, --show-apparent-size            Show apparent size
  -d, --show-disks                    Show all mounted disks
  -C, --show-item-count               Show number of items in directory
  -M, --show-mtime                    Show latest mtime of items in directory
  -B, --show-relative-size            Show relative size
      --si                            Show sizes with decimal SI prefixes (kB, MB, GB) instead of binary prefixes (KiB, MiB, GiB)
      --storage-path string           Path to persistent key-value storage directory (default is /tmp/badger) (default "/tmp/badger")
  -s, --summarize                     Show only a total in non-interactive mode
      --use-storage                   Use persistent key-value storage for analysis data (experimental)
  -v, --version                       Print version
      --write-config                  Write current configuration to file (default is $HOME/.gdu.yaml)

Basic list of actions in interactive mode (show help modal for more):
  ↑ or k                              Move cursor up
  ↓ or j                              Move cursor down
  → or Enter or l                     Go to highlighted directory
  ← or h                              Go to parent directory
  d                                   Delete the selected file or directory
  e                                   Empty the selected directory
  n                                   Sort by name
  s                                   Sort by size
  c                                   Show number of items in directory
  ?                                   Show help modal

Examples

gdu                                   # analyze current dir
gdu -a                                # show apparent size instead of disk usage
gdu --no-delete                       # prevent write operations
gdu <some_dir_to_analyze>             # analyze given dir
gdu -d                                # show all mounted disks
gdu -l ./gdu.log <some_dir>           # write errors to log file
gdu -i /sys,/proc /                   # ignore some paths
gdu -I '.*[abc]+'                     # ignore paths by regular pattern
gdu -X ignore_file /                  # ignore paths by regular patterns from file
gdu -c /                              # use only white/gray/black colors

gdu -n /                              # only print stats, do not start interactive mode
gdu -np /                             # do not show progress, useful when using its output in a script
gdu -nps /some/dir                    # show only total usage for given dir
gdu / > file                          # write stats to file, do not start interactive mode

gdu -o- / | gzip -c >report.json.gz   # write all info to JSON file for later analysis
zcat report.json.gz | gdu -f-         # read analysis from file

GOGC=10 gdu -g --use-storage /        # use persistent key-value storage for saving analysis data
gdu -r /                              # read saved analysis data from persistent key-value storage

Modes

Gdu has three modes: interactive (default), non-interactive and export.

Non-interactive mode is started automatically when TTY is not detected (using go-isatty), for example if the output is being piped to a file, or it can be started explicitly by using a flag.

Export mode (flag -o) outputs all usage data as JSON, which can be later opened using the -f flag.

Hard links are counted only once.

File flags

Files and directories may be prefixed by a one-character flag with following meaning:

  • ! An error occurred while reading this directory.

  • . An error occurred while reading a subdirectory, size may be not correct.

  • @ File is symlink or socket.

  • H Same file was already counted (hard link).

  • e Directory is empty.

Configuration file

Gdu can read (and write) YAML configuration file.

$HOME/.config/gdu/gdu.yaml and $HOME/.gdu.yaml are checked for the presense of the config file by default.

Examples

  • To configure gdu to permanently run in gray-scale color mode:
echo "no-color: true" >> ~/.gdu.yaml
  • To set default sorting in configuration file:
sorting:
    by: name // size, name, itemCount, mtime
    order: desc
  • To configure gdu to set CWD variable when browsing directories:
echo "change-cwd: true" >> ~/.gdu.yaml
  • To save the current configuration
gdu --write-config

Styling

There are wast ways how terminals can be colored. Some gdu primitives (like basic text) addapt to different color schemas, but the selected/highlighted row does not.

If the default look is not sufficient, it can be changed in configuration file, e.g.:

style:
    selected-row:
        text-color: black
        background-color: "#ff0000"

Deletion in background and in parallel (experimental)

Gdu can delete items in the background, thus not blocking the UI for additional work. To enable:

echo "delete-in-background: true" >> ~/.gdu.yaml

Directory items can be also deleted in parallel, which might increase the speed of deletion. To enable:

echo "delete-in-parallel: true" >> ~/.gdu.yaml

Memory usage

Automatic balancing

Gdu tries to balance performance and memory usage.

When less memory is used by gdu than the total free memory of the host, then Garbage Collection is disabled during the analysis phase completely to gain maximum speed.

Otherwise GC is enabled. The more memory is used and the less memory is free, the more often will the GC happen.

Manual memory usage control

If you want manual control over Garbage Collection, you can use --const-gc / -g flag. It will run Garbage Collection during the analysis phase with constant level of aggressiveness. As a result, the analysis will be about 25% slower and will consume about 30% less memory. To change the level, you can set the GOGC environment variable to specify how often the garbage collection will happen. Lower value (than 100) means GC will run more often. Higher means less often. Negative number will stop GC.

Example running gdu with constant GC, but not so aggressive as default:

GOGC=200 gdu -g /

Saving analysis data to persistent key-value storage (experimental)

Gdu can store the analysis data to persistent key-value storage instead of just memory. Gdu will run much slower (approx 10x) but it should use much less memory (when using small GOGC as well). Gdu can also reopen with the saved data. Currently only BadgerDB is supported as the key-value storage (embedded).

GOGC=10 gdu -g --use-storage /    # saves analysis data to key-value storage
gdu -r /                          # reads just saved data, does not run analysis again

Running tests

make install-dev-dependencies
make test

Profiling

Gdu can collect profiling data when the --enable-profiling flag is set. The data are provided via embedded http server on URL http://localhost:6060/debug/pprof/.

You can then use e.g. go tool pprof -web http://localhost:6060/debug/pprof/heap to open the heap profile as SVG image in your web browser.

Benchmarks

Benchmarks were performed on 50G directory (100k directories, 400k files) on 500 GB SSD using hyperfine. See benchmark target in Makefile for more info.

Cold cache

Filesystem cache was cleared using sync; echo 3 | sudo tee /proc/sys/vm/drop_caches.

CommandMean [s]Min [s]Max [s]Relative
diskus ~3.126 ± 0.0203.0873.1551.00
gdu -npc ~3.132 ± 0.0193.1113.1731.00 ± 0.01
gdu -gnpc ~3.136 ± 0.0123.1123.1551.00 ± 0.01
pdu ~3.657 ± 0.0133.6413.6771.17 ± 0.01
dust -d0 ~3.933 ± 0.1443.8494.2131.26 ± 0.05
dua ~3.994 ± 0.0733.8274.1341.28 ± 0.02
gdu -npc --use-storage ~12.812 ± 0.07812.64412.9124.10 ± 0.04
du -hs ~14.120 ± 0.21313.96914.7034.52 ± 0.07
duc index ~14.567 ± 0.08014.38514.6574.66 ± 0.04
ncdu -0 -o /dev/null ~14.963 ± 0.25414.75915.6374.79 ± 0.09

Warm cache

CommandMean [ms]Min [ms]Max [ms]Relative
pdu ~226.6 ± 3.7219.6231.21.00
diskus ~227.7 ± 5.2221.6239.91.00 ± 0.03
dust -d0 ~400.1 ± 7.1386.7409.41.77 ± 0.04
dua ~444.9 ± 2.4442.4448.91.96 ± 0.03
gdu -npc ~451.3 ± 3.8445.9458.51.99 ± 0.04
gdu -gnpc ~516.1 ± 6.7503.1527.52.28 ± 0.05
du -hs ~905.0 ± 3.9901.2913.43.99 ± 0.07
duc index ~1053.0 ± 5.11046.21064.14.65 ± 0.08
ncdu -0 -o /dev/null ~1653.9 ± 5.71645.91663.07.30 ± 0.12
gdu -npc --use-storage ~9754.9 ± 688.78403.810427.443.04 ± 3.12

Alternatives

  • ncdu - NCurses based tool written in pure C (LTS) or zig (Stable)
  • godu - Analyzer with a carousel like user interface
  • dua - Tool written in Rust with interface similar to gdu (and ncdu)
  • diskus - Very simple but very fast tool written in Rust
  • duc - Collection of tools with many possibilities for inspecting and visualising disk usage
  • dust - Tool written in Rust showing tree like structures of disk usage
  • pdu - Tool written in Rust showing tree like structures of disk usage

Notes

HDD icon created by Nikita Golubev - Flaticon