bashスクリプトでは、次のことを行います。
- すべてのログをファイルに出力します(
loglowlevel.txt
)、 - ただし、ターミナル(高レベル)に表示されるのはそのうちのいくつかだけにします。
- たとえば、20個の高レベルログと60個の低レベルログがあります。したがって、低レベルのログ「redirection-command」を無料に保ち、高レベルのログのみにリダイレクトするものを用意したいと思います。
1を取る
FD3にリダイレクトstdout
して正しく入力される基本的なスクリプトを作成しました。しかし、私は高レベルのログのオプションを指定することに固執しています。sterr
loglowlevel.txt
#!/bin/bash -
# create fd 3
exec 3<> loglowlevel.txt
# redirect stdout and stderr to fd 3
exec 1>&3
exec 2>&3
# high-level logs' redirection below is wrong
echo "high-level comment" 3>&1
# low-level logs should remain redirection-free, as below
echo "low-level comment"
ls notafile
# close fd 3
3>&-
これが何をするかです:
$ redirect.sh
$ cat loglowlevel.txt
low-level comment
ls: cannot access notafile: No such file or directory
high-level comment
ターミナルにも印刷される予定でした。
2を取る
2番目のスクリプト、異なる戦略:
#!/bin/bash -
function echolowlevel() {
echo $1 &>loglowlevel.txt
}
function echohighlevel() {
echo $1 |& tee loglowlevel.txt
}
echohighlevel "high-level comment 1"
echolowlevel "low-level comment 1"
echohighlevel "high-level comment 2"
ls notafile
これが何をするかです:
$ redirect.sh
high-level comment 1
high-level comment 2
ls: cannot access notafile: No such file or directory
$ cat loglowlevel.txt
high-level comment 2
ここでの2つの問題:
- からのエラーメッセージ
ls
はターミナルに出力されますが、私はでのみ必要loglowlevel.txt
です。 high-level comment 1
で食べられましたloglowlevel.txt
。
質問
Take1の背後にあるアイデアが好きです。しかし、2つのコマンドhigh-level comment
を保持したままstdoutに出力するにはどうすればよいですか?exec