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 .
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: So as you can see, the last line there.
11 Answer
This should work:
URL=$(gcloud run deploy loady 2>&1 |grep -o -m1 "") 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 (meaning ). 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 "") 1