0

I am writing a Bash script where I have to list the AWS access keys for a user, and then assign them to variables.

A user may have two access keys. So the user will need two variables to store those keys.

This is the line I have so far:

aws iam list-access-keys --user-name "$user_name" --profile="$aws_key"  | grep -i accesskeyid | awk '{print $2}' | sed 's/"//g'

The output would be something like this:

 AKIAJS7KDACQRQ5FJWA
 AKIAICDDTVTMEAB6RM5Q

How can I assign each of those to its own variable in Bash?

2 Answers 2

1

You can use a parameter substitution to split the string on a newline. ${variable%$'\n'*} obtains the portion of the value of $variable before the last newline, and ${variable#*$'\n'} gets the portion after the first newline.

As an aside, Awk generally can do anything grep and sed can do.

variable=$(aws iam list-access-keys --user-name "$user_name" --profile="$aws_key"  |
awk 'tolower($0) ~ /accesskeyid/{gsub(/\"/,""); print $2}')
Sign up to request clarification or add additional context in comments.

1 Comment

{ read var1; read var2; } <<< "$variable" might be simpler (or even { read var1; read var2; } < <( aws ... | awk '...').
0

You can do the processing as part of the aws command already, using a --query:

aws iam list-access-keys --user-name "$user_name" --profile="$aws_key" \
    --query 'AccessKeyMetadata[*].AccessKeyId' --output text

returns the IDs in a tab separated line, so you could do something like

read -a vars <<< \
    $(aws iam list-access-keys --user-name "$user_name" --profile="$aws_key" \
    --query 'AccessKeyMetadata[*].AccessKeyId' --output text)

and you get an array vars containing your variables.

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.