Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: check if input is empty in pipe [duplicate]

Tags:

bash

Let's say I have a bash command mycommand. Sometimes it writes something to output but always return exit code 0. I need use pipe to fix the exit code to be 0 for empty output and something else for non-empty output.

mycommand | ???

I'm not interested in ifs nor custom commands. I want just a simple command like grep with some parameters to check if its input is empty and return the exit code.

Preferably it should print the input if it is not empty but it's not mandatory.

like image 724
enumag Avatar asked Mar 19 '17 07:03

enumag


People also ask

How do you know if FIFO is empty?

When a user process attempts to read from an empty pipe (or FIFO), the following happens: If one end of the pipe is closed, 0 is returned, indicating the end of the file. If the write side of the FIFO has closed, read(2) returns 0 to indicate the end of the file.

How check if variable is empty bash?

To find out if a bash variable is empty: Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"

How do you check if output of a command is empty or not?

They use the ls -al and ls -Al commands - both of which output non-empty strings in empty directories.

What does $_ mean in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.


1 Answers

Maybe:

yourcommand | grep -qv .

! ( yourcommand |  grep -q ^ )

Or inverse meaning: return false if nothing returned:

yourcommand |  grep -q ^ || echo no output.
like image 145
F. Hauri Avatar answered Nov 15 '22 07:11

F. Hauri