LinuxCommandLibrary

ifne

Execute command only if standard input is not empty

TLDR

Run the specified command if and only if stdin is not empty

$ ifne [command] [command_options]
copy

Run the specified command if and only if stdin is empty, otherwise pass stdin to stdout
$ ifne -n [command] [command_options]
copy

SYNOPSIS

ifne [-n] command [arguments…]

PARAMETERS

-n
    Invert condition: run command only if stdin is empty.

DESCRIPTION

ifne is a utility from the moreutils package that executes a given command if and only if its standard input is not empty. It provides a simple way to make command execution conditional on the presence of input data, commonly used in pipelines to avoid running resource-intensive or noisy commands when there's no input.

By default, ifne reads one byte from stdin. If successful (stdin non-empty), it executes the specified command, passing the remaining stdin to it. If stdin is empty (read returns 0), it exits silently with status 0 without running the command.

Common use cases include:
• Piping command output to notifiers: grep pattern file | ifne notify-send "Found match"
• Conditional mailing: ./script.sh | ifne mail -s "Report" user@example.com
• Avoiding empty processing: find . -name '*.log' | ifne xargs tail -n 10

This avoids unnecessary executions, reducing noise and overhead in scripts and pipelines. Note that it works best when the executed command can handle partial stdin gracefully.

CAVEATS

Consumes the first byte of stdin if present; executed command receives remaining input (may affect commands expecting full stdin). If stdin has exactly one byte, command sees empty stdin.

EXIT STATUS

0 if condition met and command run successfully, command's exit status if run, or 0 if not run. 127 if exec fails.

EXAMPLES

grep foo log | ifne logger "Alert: foo found"
cat /dev/null | ifne -n echo "No input, skipping"

HISTORY

ifne is part of the moreutils package, developed by Joey Hess starting around 2006-2007. It addresses a common scripting need for stdin-based conditionals without complex shell constructs like if read; then .... Widely used in Debian/Ubuntu via moreutils; portable C implementation ensures efficiency.

SEE ALSO

test(1), true(1), false(1), sponge(1)

Copied to clipboard