Reputation: 457
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
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
Reputation: 295678
if output=$(something); [[ $output ]]; then
printf '%s\n' "$output" ## less-buggy alternative to echo "$output"
else
echo "Nope"
fi
Upvotes: 1