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.
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.
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"
They use the ls -al and ls -Al commands - both of which output non-empty strings in empty directories.
$_ (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.
yourcommand | grep -qv .
! ( yourcommand | grep -q ^ )
Or inverse meaning: return false if nothing returned:
yourcommand | grep -q ^ || echo no output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With