IN-Decent

Re-decentralizing internet with free software

Run Command Only When Stdin Is Not Empty

Posted at — Nov 14, 2023

ifne is a utility command which helps to avoid invoking commands when stdin is empty. ifne is not part of standard installation and can be installed by installing moreurils package as it is a tool from the moreutils package collection.

This tool extremely useful for cases when you want to check the output of a command instead of its exit code to decide whether the next command in the pipeline should be executed or not.

Take for example below battery_monitor command that I have written which will return something in the stdout only when some alert conditions are met.

The alert needs to be sent using some notifications channels like email, xmpp messages or http push notifications etc. It only needs to send notifications when there is something to notify and not send empty notifications.

I used ifne to accomplish this task as an oneliner instead of having to write a wrapper script to capture the stdout, check if it’s not empty and only then send ntfy push notifications using curl.

# alert when battery charge remaining is below a threshold
battery_monitor | ifne curl -d @- https://ntfy.sh/mytopic

NOTE: "@-" value for -d option in curl will make it read the data to POST from stdin of curl.

References:

  1. ifne manpage: https://linux.die.net/man/1/ifne
  2. moreutils homepage: https://joeyh.name/code/moreutils/