0

i have to run the following command within a script in bash and store its output in a variable. the db_name is another variable that i want to substitute too. Notice the name-db and true, i don't want my shell to start running them.

aws rds describe-db-snapshots --db-instance-identifier ${db_name} --query 'DBSnapshots[?contains(DBSnapshotIdentifier, `name-db`) == `true`]'.DBSnapshotIdentifier --output text | sort -k8 | tail -n1 | gawk '{print $4}'

I started by storing the whole command in a string and then run the string using eval or the string directly but it fails everytime. I guess it keeps expanding the true and the name-db bit. Any help ?

2
  • can you try resp=$( aws ..... ); echo $resp ? This will actually open a sub-shell and resp will contain the output. Edit: this is kinda the same as the answer from @ruakh. Commented Oct 12, 2015 at 15:24
  • Storing commands in strings does not work. See Bash FAQ 050. A function, as in ruakh's answer, is the correct solution. Commented Oct 12, 2015 at 16:49

1 Answer 1

2

Rather than storing the command in a string, you're better off storing it in a shell function:

function get_latest_foo () {
    local db_name="$1"
    aws rds describe-db-snapshots \
      --db-instance-identifier "$db_name" \
      --query 'DBSnapshots[?contains(DBSnapshotIdentifier, `name-db`) == `true`].DBSnapshotIdentifier' \
      --output text \
    | sort -k8 \
    | tail -n1 \
    | gawk '{print $4}'
}

latest_foo="$(get_latest_foo "$db_name")"

(Note: I used foo in the function-name because I couldn't tell which field $4 is. You'll want to change the name to something more meaningful.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.