Skip to content

xargs panics (index out of bounds) with -I/-i/--replace on empty input #735

Closed

Description

@leeewee

Summary

xargs -I {} CMD … (and -i, --replace) aborts (panic, exit 101) when its input is empty. In replace mode xargs runs the command once per input item; with zero items it should run nothing, but the final builder is still executed and CommandBuilder::execute unconditionally indexes extra_args[0] — which is empty — so it panics.

Steps to reproduce

$ printf '' | xargs -I {} echo hello {}
thread 'main' panicked at src/xargs/mod.rs:429:46:
index out of bounds: the len is 0 but the index is 0
$ echo $?
101

Also via -i and --replace:

$ printf '' | xargs -i echo {}
$ printf '' | xargs --replace=X echo X

Expected behavior

Match GNU: with empty input, run nothing and exit 0.

$ printf '' | /usr/bin/xargs -I {} echo hello {}
$ echo $?
0

Root cause

With the default no_run_if_empty = false, process_input always calls the final current_builder.execute() even when no items were read. In replace mode execute indexes the first extra arg:

// src/xargs/mod.rs:429
let replacement = self.extra_args[0].to_string_lossy();

extra_args is empty when no input items were read, so [0] is out of bounds.

Found by our static analysis tooling.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions