LoginSignup
3
0

More than 3 years have passed since last update.

パイプを使うとリターンコードが0になってしまう

Last updated at Posted at 2019-05-16

aws cliでjqを使うとリターンコードが0になってしまう
〇パイプを使うとリターンコードが0になってしまう

タイトル通りなのですが、コマンド実行結果によって分岐したい場面で、jqを使うとリターンコードが0になってしまいます。

結論から言うと--queryオプションを使うとよいです。

***2019/5/22追記***
jqがどうとかではなく、パイプを使用した場合は一番最後(一番右側)の処理のリターンコードが$?に格納されることが原因でした(無知でした)。そして、
$PIPESTATUSを使用することで解消できると教えていただきました。
ありがとうございます。。

例えばrdsインスタンスのパラメーターグループ名を取得するのにjqパイプを使った場合、
下記のとおりエラーにも関わらずリターンコードが0になっています。


〇成功時

$ aws rds describe-db-instances --db-instance-identifier hogeDB |jq 
"hogeDB-myrdsparamgroup-xxxxxx"
$
$ echo $?
0

✕失敗時

$ aws rds describe-db-instances --db-instance-identifier hogDB |jq '.DBInstances[].DBParameterGroups[].DBParameterGroupName'
An error occurred (DBInstanceNotFound) when calling the DescribeDBInstances operation: hogDB  not found.
$
$ echo $?
0  ← 失敗なのにリターンコードが0

$PIPESTATUSですと、パイプで区切られた処理ごとにリターンコードを配列で保持しますので、

✕失敗時

$ aws rds describe-db-instances --db-instance-identifier hogDB |jq '.DBInstances[].DBParameterGroups[].DBParameterGroupName'
An error occurred (DBInstanceNotFound) when calling the DescribeDBInstances operation: hogDB  not found.
$
$ echo "${PIPESTATUS[0]}"
255  ← うまくリターンコードが取得できました

$PIPESTATUSはLinux環境で使用できるものなので、Windows環境でしか作業できない場合は、
AWS CLIの--query オプションを使用するなど工夫する必要がありそうです。

ちなみに出力結果のダブルクォートを取りたいとき、jqだと-rオプションをつけますが、
--query オプションの場合、併せて--output text オプションをつけることで実現可能です。

$ aws rds describe-db-instances --db-instance-identifier hogeDB |jq -r '.DBInstances[].DBParameterGroups[].DBParameterGroupName'
hogeDB-myrdsparamgroup-xxxxxx
$
$
$ aws rds describe-db-instances --db-instance-identifier hogeDB --query "DBInstances[].DBParameterGroups[].DBParameterGroupName" --output text
hogeDB-myrdsparamgroup-xxxxxx
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0