Reputation: 21137
I have a command that may have an empty string as output, I want that when I execute:
myCommand | something 'default'
It either returns the output of myCommand
or default
if the output was empty
I have tried myCommand |awk '{if(\$0==""){print "default"}}'
but it doesn't always work.
Upvotes: 5
Views: 4406
Reputation: 20002
You can miss empty lines with
myCommand | grep . || echo 'default'
so you might prefer the comment of @BenjaminW. :
var=$(myCommand)
echo "${var:-default}"
Upvotes: 3
Reputation: 88646
echo foo | sed 's/^$/default/'
Output:
foo
echo | sed 's/^$/default/'
Output:
default
Upvotes: 4
Reputation: 17041
Since you mentioned awk
, here's one way.
Note this is for empty output, i.e., print the default if myCommand
outputs nothing at all. If you want to handle a program that outputs a blank line, that's something different.
myCommand | awk -v def="default" '{print} END { if(NR==0) {print def} }'
{print}
passes each input line through. At the end (END{...}
), NR
is the number of input records, i.e., the number of lines received from myCommand
. This will be 0 if no output was printed by myCommand
. If so, print the value of def
, assigned on the command line by -v def="whatever text you want"
.
Tests:
$ awk -v def="default" '{print} END {if(NR==0) {print def}}' </dev/null
default
$ awk -v def="default" '{print} END {if(NR==0) {print def}}' <<<'foo'
foo
Upvotes: 4