我正在尝试创建一个文件,并使用以下几行将其分配给变量:
aws_key="company-lab"
source_dir="source_files"
aws_role_list=$(aws iam list-roles --profile="$aws_key" | jq -r '.Roles[].RoleName' > "$source_dir"/aws-"$aws_key"-role-list.txt)
但是,当我使用变量“ $ aws_role_list”时,它是空的:
echo "echo the file"
echo "$aws_role_list"
使用bash -x运行脚本可以使您:
+ aws_role_list=
并列出如下文件:
echo "listing the file"
ls -lh "$aws_role_list"
给你:
+ ls -lh ''
ls: cannot access '': No such file or directory
我究竟做错了什么?如何正确使用aws_role_list变量?
我没有使用AWS的经验,但可以看到您正在将命令的输出重定向到文件:
aws iam list-roles --profile="$aws_key" |
jq -r '.Roles[].RoleName' > "$source_dir"/aws-"$aws_key"-role-list.txt
由于输出将进入一个文件,因此在使用时var=$(command)
,var
将其为空是合理的,因为command
它不会返回任何内容:全部都将返回"$source_dir"/aws-"$aws_key"-role-list.txt
。
因此,您要么想要这样:
aws_role_list=$(aws iam list-roles --profile="$aws_key" | jq -r '.Roles[].RoleName')
或这个:
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)
如果您试图将文件名而不是其内容获取到变量中,那么您需要这样做:
aws_key="company-lab"
source_dir="source_files"
aws_role_list="$source_dir"/aws-"$aws_key"-role-list.txt
aws iam list-roles --profile="$aws_key" |
jq -r '.Roles[].RoleName' > "$aws_role_list"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句