LoginSignup
19
23

More than 5 years have passed since last update.

[bash]時刻付きでログファイルに出力する

Last updated at Posted at 2015-07-04

[bash]時刻付きでログファイルに出力する

output2logfile.sh
#!/bin/bash

echo "Hello world"

exec 1> >(awk '{print strftime("[%Y-%m-%d %H:%M:%S]"),$0 } { fflush() } ' >>stdout.log)
exec 2> >(awk '{print strftime("[%Y-%m-%d %H:%M:%S]"),$0 } { fflush() } ' >>stderr.log)

echo "stdout"
echo "stderr" >&2

exit 0
実行結果
# ./output2logfile.sh
Hello world
#
# ls -l
合計 12
-rwxr-xr-x 1 root root 250  7月  5 06:40 2015 output2logfile.sh
-rw-r--r-- 1 root root  29  7月  5 06:52 2015 stderr.log
-rw-r--r-- 1 root root  29  7月  5 06:52 2015 stdout.log
#
# cat stdout.log
[2015-07-05 06:52:03] stdout
#
# cat stderr.log
[2015-07-05 06:52:03] stderr
#

参考情報

  1. bashのプロセス置換機能を活用して、シェル作業やスクリプト書きを効率化する
  2. シェルスクリプトが '> $logfile 2>&1' だらけにならなくて済んだ話
  3. (今さら) vmstat の結果に時間をつけてファイルに出力する
19
23
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
19
23