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

Jos*_*shZ 7 shell bash aws-cli

我正在尝试aws ec2 delete-snapshot在 Bash 脚本命令中捕获 a 的输出,但我无法获得任何东西来捕获输出。我已经尝试过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:~#
Run Code Online (Sandbox Code Playgroud)

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

有没有其他人遇到过这个问题?

Wil*_*ill 10

所述>操作者仅重定向stdout(“标准输出”),或“文件描述符1”。错误消息通常打印在不同的文件描述符上,2, stderr, (“标准错误”)。在您的终端屏幕上,您会同时看到stdoutstderr

>运营商确实是更多的只是一个快捷方式1>,并再次,只有重定向stdout。该2>运算符类似于,1>但它不是重定向stdout,而是重定向stderr

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$
Run Code Online (Sandbox Code Playgroud)

所以,既重定向stdoutstderr以相同的文件,使用>file 2>&1

user@host$ echo hi 2>/dev/null 1>&2
user@host$
Run Code Online (Sandbox Code Playgroud)

这表示,“将回声重定向stderr/dev/null,然后重定向stdout到 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$ 
Run Code Online (Sandbox Code Playgroud)

在现代 Bash 中,您还可以使用&>将两个流重定向到同一个文件:

user@host$ curl --invalid-option-show-me-errors &>/dev/null
user@host$ 
Run Code Online (Sandbox Code Playgroud)

所以对你来说,特别是,使用:

aws ec2 delete-snapshot --snapshot-id vid --output json >test 2>&1
Run Code Online (Sandbox Code Playgroud)

或者

aws ec2 delete-snapshot --snapshot-id vid --output json &>test
Run Code Online (Sandbox Code Playgroud)


Cra*_*ell 5

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

aws ec2 delete-snapshot --snapshot-id vid --output json >test 2>&1
Run Code Online (Sandbox Code Playgroud)


小智 5

如果您想在变量中捕获 stdout 和 stderr,请尝试:

RESULT="$(aws ec2 delete-snapshot --snapshot-id vid --output json 2>&1)"

if ! [[ $RESULT =~ "Successfully deleted snapshot" ]]; then
  echo "ERROR while deleting snapshot"
  echo "$RESULT"
  exit 1
fi

...
Run Code Online (Sandbox Code Playgroud)