为什么我无法在Bash中捕获AWS EC2 CLI输出?

我试图在Bash脚本命令中捕获aws ec2 delete-snapshot的输出,但是我无法获取任何东西来捕获输出。 我试过result=$(command)result=`command` result=$(command) result=`command`等,但是当我尝试echo $result没有什么。

这里是一些输出示例。

 root@host:~# aws ec2 delete-snapshot --snapshot-id vid --output json>test A client error (InvalidParameterValue) occurred when calling the DeleteSnapshot operation: Value (vid) for parameter snapshotId is invalid. Expected: 'snap-...'. root@host:~# aws ec2 delete-snapshot --snapshot-id vid>test A client error (InvalidParameterValue) occurred when calling the DeleteSnapshot operation: Value (vid) for parameter snapshotId is invalid. Expected: 'snap-...'. root@host:~# cat test root@host:~# testing=$(aws ec2 delete-snapshot --snapshot-id vid) A client error (InvalidParameterValue) occurred when calling the DeleteSnapshot operation: Value (vid) for parameter snapshotId is invalid. Expected: 'snap-...'. root@host:~# echo $testing root@host:~# 

我需要自动创build和删除快照,但我无法捕获输出。

有没有人遇到这个问题?

>运算符只redirectstdout (“标准输出”)或“文件描述符1 ”。 错误消息通常打印在不同的文件描述符2stderr (“标准错误”)上。 在你的terminal屏幕上,你可以看到stdoutstderr

>运算符实际上只是1>一个快捷方式,而且只是redirectstdout2>运算符与1>类似,但它不是redirectstdout ,而是redirectstderr

 user@host$ echo hello world >/dev/null user@host$ echo hello world 1>/dev/null user@host$ echo hello world 2>/dev/null hello world user@host$ 

因此,要将stdoutstderrredirect到同一个文件,请使用>file 2>&1

 user@host$ echo hi 2>/dev/null 1>&2 user@host$ 

这就是说,“将echo的stderrredirect到/dev/null ,并将stdoutredirect到stderr。

 user@host$ curl --invalid-option-show-me-errors >/dev/null curl: option --invalid-option-show-me-errors: is unknown try 'curl --help' or 'curl --manual' for more information user@host$ curl --invalid-option-show-me-errors 2>/dev/null user@host$ user@host$ curl --invalid-option-show-me-errors >/dev/null 2>&1 user@host$ 

在现代Bash中,您也可以使用&>将两个streamredirect到同一个文件:

 user@host$ curl --invalid-option-show-me-errors &>/dev/null user@host$ 

所以对你来说,具体来说就是用:

 aws ec2 delete-snapshot --snapshot-id vid --output json >test 2>&1 

要么

 aws ec2 delete-snapshot --snapshot-id vid --output json &>test 

错误输出将写入stderr ,而不是stdout ,而您只是redirectstdout 。 如果您还想捕获stderr ,则需要添加2>&1 ,例如:

 aws ec2 delete-snapshot --snapshot-id vid --output json >test 2>&1