ifne
Execute command only if standard input is not empty
TLDR
Run the specified command if and only if stdin is not empty
Run the specified command if and only if stdin is empty, otherwise pass stdin to stdout
SYNOPSIS
ifne [OPTION]... COMMAND [ARGUMENT]...
PARAMETERS
COMMAND
The command to be executed conditionally.
ARGUMENT...
Arguments to be passed to the COMMAND.
-n
Execute the command even if standard input is empty. This effectively negates the default behavior, running the command regardless of input.
-x
Execute the command and pass the content of standard input as arguments to the command, similar to xargs. This option implicitly forces the command to run if there is input, regardless of the -n option.
--version
Display version information and exit.
--help
Display a help message and exit.
DESCRIPTION
ifne (short for "if not empty") is a utility from the moreutils package that provides a simple yet powerful way to conditionally execute a command. Its primary function is to read from its standard input (stdin) and then, based on whether stdin contains any data, decide whether to run the specified command. If stdin is not empty, the command is executed. If stdin is empty, the command is not executed.
This makes ifne particularly useful in shell scripting and pipelines where you want to avoid running a subsequent command unnecessarily or to prevent errors from commands that expect input but receive none. It effectively acts as a gatekeeper for commands in a pipeline. For instance, you might use it to send an email only if a log file contains specific error messages, or to process a list of files only if the list is non-empty.
CAVEATS
ifne reads its entire standard input into memory before deciding whether to execute the command. For extremely large inputs, this could potentially consume significant memory. It also means that the command isn't executed until all of its input has been received, which might not be suitable for streaming or very long-running processes where immediate processing of input is required.
HOW <I>IFNE</I> DIFFERS FROM <I>XARGS</I>
While ifne -x can pass input as arguments like xargs, their primary purposes differ. ifne's core function is conditional execution: it runs a command only if there's input. xargs, on the other hand, always attempts to execute a command, breaking down large inputs into multiple command invocations if necessary. xargs is about processing input in batches, whereas ifne is about making a single decision based on input presence.
HISTORY
ifne is part of the moreutils package, a collection of small, useful Unix utilities that operate on lines. moreutils was created by Joey Hess, and its utilities are designed to fill common gaps in standard Unix tools, often by providing simple, single-purpose commands that can be easily combined in pipelines. ifne specifically addresses the common scripting need for conditional execution based on the presence of input.