20

Messing around with a simple aws cli query to check for the existence of a Lambda function and echo the associated role if it exists:

#!/bin/bash

fname=$1
role=$(aws lambda list-functions --query 'Functions[?FunctionName == `$fname`].Role' --output text)

echo "$fname role: $role"

However, $fname appears to be resolving to an empty string in the aws command. I've tried escaping the back ticks, swapping ` to ' and a miriad of other thrashing edits (and yes, I'm passing a string on the cl when invoking the script :)

How do I properly pass a variable into JMESPath query inside a bash script?

Sean Bright
  • 118,630
  • 17
  • 138
  • 146
TomH
  • 2,950
  • 2
  • 26
  • 49

2 Answers2

35

Because the whole JMESPath expression is enclosed in single quotes, bash is not expanding the $fname variable. To fix this you can surround the value with double quotes and then use single quotes (raw string literals) for the $fname var:

aws lambda list-functions --query "Functions[?FunctionName == '$fname'].Role" --output text
jamesls
  • 5,428
  • 1
  • 28
  • 17
10

Swapping the backticks to single quotes, didn't work for me... :(

But escaping the backticks works :)

Here are my outputs:

aws elbv2 describe-listeners --load-balancer-arn $ELB_ARN --query "Listeners[?Port == '$PORT'].DefaultActions[].TargetGroupArn | [0]"

null

aws elbv2 describe-listeners --load-balancer-arn $ELB_ARN --query "Listeners[?Port == \`$PORT\`].DefaultActions[].TargetGroupArn | [0]"

"arn:aws:elasticloadbalancing:ap-southeast-2:1234567:targetgroup/xxx"

jobwat
  • 8,527
  • 4
  • 31
  • 30
  • 1
    That's because raw quotes (single quotes) *always create strings*, and if `Listeners[].Port` is a number, then a string won't match. That is, '1234' is really short for \`"1234"\`. – Mark Reed Apr 10 '19 at 13:31