Home > front end >  Pipe multiple lines from output as multiple exports
Pipe multiple lines from output as multiple exports

Time:02-04

When I use

<some commands that output a json> | jq -r '.Credentials | .AccessKeyId, .SecretKey, .SessionToken'

I get the following output:

ABCDEF
123456
AAAAAABBBBBAAAAAABBBBBAAAAAABBBBBAAAAAABBBBBAAAAAABBBBBAAAAAABBBBBAAAAAABBBBBAAAAAABBBBBAAAAAABBBBBAAAAAABBBBBAAAAAABBBBBAAAAAABBBBBAAAAAABBBBBAAAAAABBBBBAAAAAABBBBBAAAAAABBBBBAAAAAABBBBBAAAAAABBBBBAAAAAABBBBBAAAAAABBBBB

Three distinct lines with various keys.

I would like to export these outputs as exports:

export AWS_ACCESS_KEY_ID=<the first line of the output>
export AWS_SECRET_KEY=<the second line of the output>
export AWS_SESSION_TOKEN=<the third line of the output>

How do I do that (and still remain with oneliner)?

I tried doing the following:

<some commands that output a json> | jq -r '.Credentials | .AccessKeyId, .SecretKey, .SessionToken' | export AWS_ACCESS_KEY_ID=`awk 'NR==1'`

and it works but

<some commands that output a json> | jq -r '.Credentials | .AccessKeyId, .SecretKey, .SessionToken' | export AWS_ACCESS_KEY_ID=`awk 'NR==1'; export AWS_SECRET_KEY=`awk 'NR==2'`

hangs.

I'm using zsh.

CodePudding user response:

You can use something like this:

read AWS_ACCESS_KEY_ID AWS_SECRET_KEY AWS_SESSION_TOKEN << EOF
$(<some commands that output a json> | jq -r '.Credentials | .AccessKeyId, .SecretKey, .SessionToken' | tr '\n' ' ')
EOF
export AWS_ACCESS_KEY_ID AWS_SECRET_KEY AWS_SESSION_TOKEN

CodePudding user response:

I'd do it like this:

for i in AWS_ACCESS_KEY_ID AWS_SECRET_KEY AWS_SESSION_TOKEN; do
    read "$i" && export "$i"
done \
< <(json commands |
jq -r '...')

The variables are only exported if something is successfully read. If you want them exported regardless (empty), just remove the "and" operator (&&).

  •  Tags:  
  • Related