arraysbashsubshellifsshellcheck

SC2207 Bash array assignment from subshell not splitting as expected


I have been populating an array using:

AWS_STS_CREDS=( $(aws sts ...) )

This raises shellcheck error SC2207

Prefer mapfile or read -a to split command output

But the recommendation does not work as expected.

IFS=" " read -r -a AWS_STS_CREDS <<< "$(
  aws sts assume-role \
    --role-arn ${AWS_ROLE_ARN} --role-session-name ${AWS_SESSION_NAME} \
    --query '[Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken]' \
    --output text
)"

echo "Array contains ${#AWS_STS_CREDS[@]} elements"
#> Array contains 1 elements

echo "${AWS_STS_CREDS[0]}"
#> ASIAV2R3U... 4gXdep/GN... FwoGZXI...

I have also tried removing the quotes around the subcommand.

At first it appears as though the set IFS is having no effect but the below works:

IFS=" " read -r -a AWS_STS_CREDS <<< "$(echo '1 2 3')"

I am overlooking something but I'm having trouble identifying the problem and would like to understand the behaviour.


Solution

  • As per @Cyrus's suggestion, piping the subcommand output to cat -A clearly shows it is tab delimited. Indicated by ^I

    echo "${AWS_STS_CREDS[0]}"
    #> ASIAV2R3U...^I4gXdep/GN...^IFwoGZXI...
    

    Amending the script as follows works as expected:

    IFS=$'\t' read -r -a AWS_STS_CREDS <<< "$(
      aws sts assume-role \
        --role-arn ${AWS_ROLE_ARN} --role-session-name ${AWS_SESSION_NAME} \
        --query '[Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken]' \
        --output text
    )"
    
    echo "Array contains ${#AWS_STS_CREDS[@]} elements"
    #> Array contains 3 elements
    
    echo "${AWS_STS_CREDS[0]}"
    #> ASIAV2R3U...