Jason Stanley
Jason Stanley

Reputation: 457

Print output of command if output is not null else echo no output

I am running a command in bash. I would like to run the command only once.

If the command has an output, print the output. But if there is no output, echo out something like No output

My command is

gcloud projects get-iam-policy sap-development  --flatten="bindings[].members" --format='table(bindings.role)' --filter="bindings.members: user:[email protected]"

If there is a result, it prints an output. If there is no result, nothing is printed in the output.

I could do something like

if [[ $(gcloud projects get-iam-policy <PROJECT>  --flatten="bindings[].members" --format='table(bindings.role)' --filter="bindings.members: user:[email protected]" ) ]] 
then
    gcloud projects get-iam-policy <PROJECT>  --flatten="bindings[].members" --format='table(bindings.role)' --filter="bindings.members: user:[email protected]"
else
    echo "No permissions found"
fi

But I find this too redundant. Is there an alternative where I can use the command only once ?

Upvotes: 0

Views: 291

Answers (2)

Gordon Davisson
Gordon Davisson

Reputation: 125998

Yet another option:

gcloud ... | { grep '.*' || echo "No output"; }

How it works: the grep matches and prints everything it gets over the pipe; if it doesn't find anything it exits with a failure status, in which case the echo runs.

Upvotes: 0

Charles Duffy
Charles Duffy

Reputation: 295678

if output=$(something); [[ $output ]]; then
  printf '%s\n' "$output"  ## less-buggy alternative to echo "$output"
else
  echo "Nope"
fi

Upvotes: 1

Related Questions