シェルスクリプトで実行するときにファイルにMySQL結果メタデータをキャプチャする方法

シェルスクリプトで実行するときにファイルにMySQL結果メタデータをキャプチャする方法

Linux(CentOS 7)のシェルスクリプトでMySQLスクリプトファイルを実行しています。結果をファイルにキャプチャできますが、結果のメタデータはキャプチャできません。

例:

私のtest.sqlファイルは次のとおりです。

USE dbname;
SELECT * FROM `test`;
INSERT INTO test values (3,'Test');

私のtest.shスクリプトは次のとおりです

#!/bin/bash
    
mysql --password=<pwd> --user=<username> --host=<host domain> < test.sql > out.txt

コマンドラインからtest.shを実行するとキャプチャできますが、out.txtMySQLはコマンドの影響を受ける行数などのメタデータも生成しますINSERT。 。

ベストアンサー1

詳細レベルを上げることができます。これで十分です。

-vv

理由:

確認するisatty端末に印刷されない場合は、バッチモードに入ります。man詳細レベル--help

--verbose 
 -v       Verbose mode. Produce more output about what the program
          does. This option can be given multiple times to produce
          more and more output. (For example, -v -v -v produces 
          table output format even in batch mode.)

--batch
-B        Print results using tab as the column separator, with each
          row on a new line. With this option, mysql does not use 
          the history file.

          Batch mode results in nontabular output format and escaping
          of special characters. Escaping may be disabled by using 
          raw mode; see the description for the --raw option.

あなたが望むものに応じて、あなたもそれをしたいと思います--raw


ウサギを追う

ttyそれ以外の場合は、次のように偽造する必要がありますscript

0<&- script -qefc "mysql -u user --password='xxx' --host=host"< test.sql >out.txt

それはキャプチャします。すべて- ところでまた誰かはそれを望むかもしれませんね。


入力を除外

library を使用してisatty()フラグをオーバーライドしないプログラムの場合は、tty次のように偽造することもできます(最小Cコードスニペットのコンパイル)。

echo 'int isatty(int fd) { return 1; }' | \
gcc -O2 -fpic -shared -ldl -o faketty.so -xc -

strip faketty.so # not needed, but ...

chmod 400 faketty.so # not needed, but ...

次に、次を実行します。

LD_PRELOAD=./faketty.so mysql -u user --password='xxx' --host=host< test.sql >out.txt

または、次のシェルラッパーを追加しますfaketty

#! /bin/sh -
LD_PRELOAD=/path/to/faketty.so "$@"

それから

$ faketty mysql ... < foo >bar

おすすめ記事