Filter output and set variable
I would like to run a bash script which invokes a command and then sets a variable in the script with a part of the output from the first command. In my case I would like to set the variable URL
to https://loady-7jmiymbtlg-uc.a.run.app
.
my-script.sh
:
gcloud run deploy loady
# echo $URL <--- how to set this with the output from the above command
When I run my script (example output):
karl@Karls-MacBook-Pro ~ $ ./my-script.sh
Deploying container to Cloud Run service [loady] in project [loady] region [us-central1]
✓ Deploying new service... Done.
✓ Creating Revision...
✓ Routing traffic...
✓ Setting IAM Policy...
Done.
Service [loady] revision [loady-00001-nod] has been deployed and is serving 100 percent of traffic.
Service URL: https://loady-7jmiymbtlg-uc.a.run.app
So as you can see, the last line there.
This should work:
URL=$(gcloud run deploy loady 2>&1 |grep -o -m1 "https://\S*")
The 2>&1
merges the stdout and stderr outputs of the gcloud
command into stdout, needed for |
to filter both through grep
should that be necessary.
grep
will output only (-o
) the first (-m1
) url matching the regular expression https://\S*
(meaning https://everything.until.before/next/space
). The final stdout of the contents of $()
is invisibly stored in $URL
.
Since stderr isn't captured by $()
or |
, you can choose to still also display the output of the gcloud
command by duplicating it all back to stderr with tee
.
URL=$(gcloud run deploy loady 2>&1 |tee /dev/stderr |grep -o -m1 "https://\S*")