[英]cant suppress or use an AWS-CLI error in bash
i have a simple script that i want to display specific information from AWS using AWS CLI.我有一个简单的脚本,我想使用 AWS CLI 显示来自 AWS 的特定信息。
for example:例如:
get_cluster_name() {
EKS_NAME=$(aws eks describe-cluster --name ${CUSTOMER_NAME}) && \
echo $EKS_NAME | jq -r .cluster.name}
the output when the cluster exist is ok, i get the name of the cluster.集群存在时的输出正常,我得到了集群的名称。
when the cluster does not exist, i get:当集群不存在时,我得到:
An error occurred (ResourceNotFoundException) when calling the DescribeCluster operation: No cluster found for name: example_cluster.
my goal is to get an empty output when a cluster is not found.我的目标是在未找到集群时获得空输出。 for that i wanted to use the return code in a condition or a string lookup in the output.为此,我想在输出中的条件或字符串查找中使用返回码。
the issue is that the output is not stdout or stderr, therefor i cant even direct it to /dev/null just to silence the error.问题是输出不是标准输出或标准错误,因此我什至不能将它指向 /dev/null 只是为了消除错误。
how can i make this code work properly?:我怎样才能使这段代码正常工作?:
[[ $(get_cluster_name) =~ "ResourceNotFoundException" ]] && echo "EKS Cluster:....$(get_cluster_name)"
or要么
[[ $(get_cluster_name) ]] && echo "EKS Cluster:....$(get_cluster_name)"
Thank you.谢谢你。
Here's a consideration, and expansion on my comments.这是对我的评论的考虑和扩展。 Again you're getting a stderr
response when no cluster is found, so this makes this pretty straightforward.当未找到集群时,您将再次收到stderr
响应,因此这非常简单。
Using >2 /dev/null
to suppress that return message in stderr.使用>2 /dev/null
抑制 stderr 中的返回消息。 Then using ret=$?
然后使用ret=$?
to capture the return code.捕获返回码。
get_cluster_name() {
EKS_NAME=$(aws eks describe-cluster --name ${CUSTOMER_NAME} 2> /dev/null);
ret=$?
if [ $ret -eq 0 ]; then
echo $EKS_NAME | jq -r .cluster.name
return 0
else
return $ret
fi
}
You can do the same thing now when you call the function as your error will propagate from aws
command up the stack:您现在可以在调用该函数时执行相同的操作,因为您的错误将从aws
命令向上传播到堆栈:
cluster=$(get_cluster_name)
ret=$?
if [ $ret -eq 0 ]; then
echo $cluster
else
echo "failed to find cluster. Error code: $ret"
fi
As an example.举个例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.