LoginSignup
0
2

More than 1 year has passed since last update.

コマンドがパイプされているかどうかをチェックする

Posted at

aptコマンドをパイプすると警告がでる

Ubuntuなどで apt コマンドをパイプすると, こういうWARNINGが出ます.

$ apt list --installed | grep apt

WARNING: apt does not have a stable CLI interface. Use with caution in scripts.

スクリプトやDockerfileなどでaptコマンドを使いたいなら, 安定したapt-getコマンドを代わりに使うべき, ということになります.

コマンドがパイプされているかどうかの判定方法

ところで, コマンドの実行結果がパイプされているかどうかって, どう判定するのでしょうか.

aptの実装

aptの実装は次のようになっています.

if(!isatty(STDOUT_FILENO) &&
   _config->FindB("Apt::Cmd::Disable-Script-Warning", false) == false)
{
   std::cerr << std::endl
             << "WARNING: " << flNotDir(argv[0]) << " "
             << "does not have a stable CLI interface. "
             << "Use with caution in scripts."
             << std::endl
             << std::endl;
}

有り体にいうと, isatty 関数で判定しています.
これが false なら, パイプされているという意味.

pythonで実装するなら?

file like object が でisatty が使えるので, それで判定できます.

import sys

if not sys.stdout.isatty():
    print("warning", file=sys.stderr)

シェルでやるなら?

とりあえずbashで.

testコマンドで判定できます.
-t にファイルディスクリプタを渡すと, それがターミナルに関連付けられているかどうかをチェックできます.
(false ならパイプされている)
(標準出力のファイルディスクリプタは 「1」)

-t FD file descriptor FD is opened on a terminal

if ! test -t 1; then # [ ! -t 1 ] も同じ
    echo "warning" >&2
fi
0
2
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
0
2