2014-12-03 24 views
0

我在bash腳本中執行一些API調用。在這種情況下,如果API調用成功,則返回json文件,如果失敗,則返回stderr。我想捕獲stderr並解決它在一個失敗。因此,在回顧了很多答案之後,我發現迄今爲止沒有任何組合可行。如果在執行腳本時出錯,如何將stderr捕獲到變量中?

舉例來說,我已經添加下面的規則,所以當我運行:

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和標準錯誤下面返回。所以現在我想解析消息來檢查它是否是一個一般性錯誤或重複:

客戶端錯誤(InvalidPermission.Duplicate)調用 AuthorizeSecurityGroupIngress操作時發生:指定的規則「同行: 0.0.0.0/0,TCP,距離Port:80端口:80,允許」已經存在

+0

要捕獲stderr,您應該使用'$ {myCmd [@]}> myJson.file 2> myJson.err'並在'then'子句的主體中使用'myJson.err'。 – Jdamian 2014-12-03 08:37:57

回答

1
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 
+1

將此作爲正確的答案,因爲它運行cmd並將通過/失敗解析爲if/else在一行中,所以我不需要做任何進一步的測試。 – 2014-12-03 08:51:11

1

使用此:

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

2>&1重定向stderr連接到哪裏stdout已連接,這是用於命令替換的管道。由於重定向是從左向右處理的,因此在將stdout重定向到文件之前會發生這種情況。

然後,您可以解析錯誤消息$message

+0

感謝@Barmar感謝快速回復,這確實有效,但我必須按照我的原始代碼進行額外的步驟測試,與sputnick的答案相比,這樣可以使整個模塊變得更簡單 – 2014-12-03 08:53:25

+0

您可以使用以下方法做同樣的事情:如果消息= $(...)'。 – Barmar 2014-12-03 08:55:31

相關問題