実行中のスクリプトからの標準出力リダイレクト

実行中のスクリプトからの標準出力リダイレクト

Cでは、プログラムの実行中にstdoutを特定の場所にリダイレクトできます。たとえば、次のようになります。

int fd = open("some_file", O_RDWR);
dup2(fd, STDOUT_FILENO);
printf("write to some_file\n");

./script.sh > some_filebashスクリプト()を実行するときにstdoutをリダイレクトせずにbashでこれを達成できますか?

ベストアンサー1

あなたはそれを使用することができますリダイレクト複合コマンドを含むすべてのコマンドの周り。たとえば、

some_function () {
  echo "This also $1 to the file"
}

{
  echo "This goes to the file"
  some_function "goes"
} >some_file
echo "This does not go to the file"
some_function "does not go"

次のコマンドを呼び出して永続的なリダイレクトを実行できます(スクリプトが終了するか、別のリダイレクトで上書きされるまで)。exec組み込みリダイレクトはありますが、コマンドはありません。たとえば、

foo () {
  echo "This does not go to the file"
  exec >some_file
  echo "This goes to the file"
}
foo
echo "This still goes to the file"

これらの機能は、bashを含むすべてのBourne / POSIXスタイルのシェルで利用できます。

おすすめ記事