bluethundr
bluethundr

Reputation: 1345

split output of bash array into lines

I'm writing a bash script that takes a user name from user input, and displays their AWS access keys and creation dates.

I use jq to parse the output of the command.

The output looks like this:

Enter a user name: 
ralph
User ralph keys:
AKIAJS7KPHZCQRQ5FJWA
2016-08-31T15:38:18Z
AKIAICDOHVTMEAB6RM5Q
2018-02-08T03:55:51Z

How can I split that output so that the access key is listed next to the date?

I want the output to look like this:

AKIAJS7KPHZCQRQ5FJWA : 2016-08-31T15:38:18Z
AKIAICDOHVTMEAB6RM5Q : 2018-02-08T03:55:51Z

This is my code so far:

echo "Enter a user name: "
   read -r user_name

   keys=( $(aws iam list-access-keys --profile=prod  | jq -r '.AccessKeyMetadata[] | (.AccessKeyId, .CreateDate)') )

   echo "User $user_name keys:"
   for key in "${keys[@]}"
     do
       echo "$key"
   done

Upvotes: 2

Views: 164

Answers (2)

keithpjolley
keithpjolley

Reputation: 2273

(note that I changed the aws iam command just a bit.)

$ aws iam list-access-keys  | jq -r '.AccessKeyMetadata[] | (.AccessKeyId, .CreateDate)' | awk 'NR%2{k=$0;next}{print k " : " $0}'
AKIAIXXXXXXXXX : 2014-10-07T14:56:12Z
AKIAIYYYYYYYYY : 2015-01-10T12:18:01Z

In other words, get rid of the loop:

echo "Enter a user name: "
read -r user_name
echo "User $user_name keys:"

aws iam list-access-keys --profile=kpmg-prod  \ 
| jq -r '.AccessKeyMetadata[] | (.AccessKeyId, .CreateDate)') \
| awk 'NR%2{k=$0;next}{print k " : " $0}'

If you are doing something else in that loop:

n=0
for i in $(aws iam list-access-keys  | jq -r '.AccessKeyMetadata[] | (.AccessKeyId, .CreateDate)')
do
  if [ $n -eq 0 ]; then
    id="$i"
    let n=1+$n
  else
    n=0
    date="$i"
    echo "$id : $date"
  fi
done

Upvotes: 2

romaric crailox
romaric crailox

Reputation: 584

You can try to use tr '\n' ':' that I guess will replace newline caracter by ':' within keys variable

Upvotes: 1

Related Questions