Rad4
Rad4

Reputation: 2384

Bash command for setting aws command output to a variable

I want to assign a variable in shell script for the below aws command.. If the command is successful,I want to assign the output to S3_BUCKET_REGION.Eg: S3_BUCKET_REGION = us-east-1.

S3_BUCKET_REGION=$( aws s3api get-bucket-location --bucket ${TF_STATE_S3_BUCKET} | jq -r '.LocationConstraint // "us-east-1"' )

But if the bucket does not exist,the error for the above command is "An error occurred (NoSuchBucket) when calling the GetBucketLocation operation: The specified bucket does not exist"

I want to capture this error and echo it in the script.

So if the command runs successfully,I want to assign to a variable.If not ,I want to echo the error.How to do conditional statement for this?

Upvotes: 0

Views: 357

Answers (1)

Saboteur
Saboteur

Reputation: 1428

Usually commands sends output to STDOUT and errors to STDERR. $() grabs only STDOUT, so you should finish your command with redirection of STDERR to STDOUT

MYVAR=$( blablabla 2>&1 )

Upvotes: 1

Related Questions