I'm trying to create a file and assign it to a variable with these lines:

aws_role_list=$(aws iam list-roles --profile="$aws_key" | jq -r '.Roles[].RoleName' > "$source_dir"/aws-"$aws_key"-role-list.txt)

But when I go to use the variable "$aws_role_list" it's empty:

echo "echo the file"
echo "$aws_role_list"

Running the script with bash -x gives you:

+ aws_role_list=

And listing the file like this:

echo "listing the file"
ls -lh "$aws_role_list"

Gives you:

+ ls -lh ''
ls: cannot access '': No such file or directory

What am I doing wrong? How can I use the aws_role_list variable correctly?

  • The question is not how to use aws_role_list variable correctly. It is what is causing the variable to not have any value. Decompose the command and see where things fail. – Lewis M Oct 9 '18 at 14:20

I have no experience with AWS, but I can see that you are redirecting a command's output to a file:

aws iam list-roles --profile="$aws_key" | 
    jq -r '.Roles[].RoleName' > "$source_dir"/aws-"$aws_key"-role-list.txt

Since the output is going into a file, when you use var=$(command), it is reasonable that var will be empty because command doesn't return anything: it's all going to "$source_dir"/aws-"$aws_key"-role-list.txt.

So, you either want this:

aws_role_list=$(aws iam list-roles --profile="$aws_key" | jq -r '.Roles[].RoleName')

Or this:

aws iam list-roles --profile="$aws_key" | 
    jq -r '.Roles[].RoleName' > "$source_dir"/aws-"$aws_key"-role-list.txt
aws_role_list=$(cat "$source_dir"/aws-"$aws_key"-role-list.txt)

If you are trying to get the file's name and not its contents into the variable, then you want this:

aws iam list-roles --profile="$aws_key" | 
    jq -r '.Roles[].RoleName' > "$aws_role_list"
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.