0

我正在 bash 脚本中执行一些 API 调用。在这种情况下,如果 API 调用成功,则json返回一个文件,如果失败stderr则返回一个文件。我想捕获stderr并在失败时解析它。在查看了很多关于 SO 的答案后,我发现到目前为止没有任何组合有效。

例如,我已经添加了以下规则,所以当我运行时:

myCmd=("aws --profile myProfile --region eu-west-1 ec2 authorize-security-group-ingress --group-id sg-999aa999 --protocol tcp --port 80 --cidr 0.0.0.0/0 ")
${myCmd[@]} > myJson.file

#check if success
if [ "$?" -ne "0" ] 
then
   # PARSE STDERR
fi

成功检查返回 255 并且 stderr 在下面返回。所以现在我想解析消息以检查它是一般错误还是重复:

调用 AuthorizeSecurityGroupIngress 操作时发生客户端错误(InvalidPermission.Duplicate):指定规则“peer: 0.0.0.0/0, TCP, from port: 80, to port: 80, ALLOW”已经存在

4

2 回答 2

2
myCmd=("aws --profile myProfile --region eu-west-1 ec2 authorize-security-group-ingress --group-id sg-999aa999 --protocol tcp --port 80 --cidr 0.0.0.0/0 ")

if "${myCmd[@]}" > myJson.file 2> error.file; then
   echo ok
else
    err="$(cat error.file)"
    # do domething with $err
fi
于 2014-12-03T08:38:50.237 回答
2

用这个:

message=$(${myCmd[@]} 2>&1 >myJson.file)

2>&1重定向stderrstdout连接的位置,这是用于命令替换的管道。由于重定向是从左到右处理的,这发生在stdout重定向到文件之前。

然后,您可以解析$message.

于 2014-12-03T08:40:01.227 回答