cron
今後、ジョブとして設定するbashスクリプトを作成しました。
echo
スクリプトの開発中に、次のコードスニペットのようにコードを追跡してデバッグするのに役立ついくつかの行を追加しました。
#!/bin/bash
# Check to see if a LOG file exists
if [ -f $LOGDIR/$LOG_FILE ]; then
echo "LOG file exists"
# Clear the contents of the LOG file if already present
echo -n "" > $LOGDIR/$LOG_FILE
elif [ ! -f $LOGDIR/$LOG_FILE ]; then
echo "LOG file does not exist. Creating now..."
touch $LOGDIR/$LOG_FILE
if [ $? -eq 0 ]; then
echo "LOG file created successfully"
elif [ ! $? -eq 0 ]; then
echo "Unable to create file. Logging disabled"
fi
fi
echo
cron job
ユーザーはその行を見ることができないので、設定した後にこの行をコメントアウトする必要があるかどうか疑問に思います。また、ラインcron job
で実行するときのecho
パフォーマンスに影響があるかどうかはわかりません。
これを実装するときにいくつかの良いケースを知りたいですcron jobs
。ありがとうございます。
ベストアンサー1
実行するかどうかにかかわらず、標準のコーディング方法をここに適用する必要がありますcron
。例えば、
- 変数を使用するときに二重引用符を使用すると、シェルが単語分割やワイルドカードを実行する機会はありません。
- 一般的な大文字の環境変数と競合しないように、大文字全体の代わりに小文字の変数名を使用することを目的としています。
- デバッグ文の作成標準エラー、通常のプログラムフローを自由に使用できます。標準出力
次のようにスニペットを作成できます。
#!/bin/bash
logDir=...
logFile=...
DBG=false # or "true"
# Check to see if a LOG file exists
if [ -f "$logDir/$logFile" ]
then
$DBG && echo "Log file exists: $logDir/$logFile" >&2
> "$logDir/$logFile"
else
echo "Log file does not exist. Creating: $logDir/$logFile" >&2
if touch "$logDir/$logFile"
then
echo "Log file created successfully" >&2
else
echo "Unable to create file. Logging disabled" >&2
fi
fi
個人的には、テストされていないこのバージョンと同様に、ロギング関数でラップします。
#!/bin/bash
log() {
local dt=$(date +'%Y%m%d_%H%M%S') toTerm=false msg=
# "+" prefix mandates writing to stderr
[ "$1" = + ] && toTerm=true && shift
msg=$(
if [ $# -gt 0 ] then
printf '%s: %s\n' "$dt" "$*"
else
sed "s/^/$dt: /"
fi
)
# write to stderr if mandated or enabled
if ${logTerm:-false} || $toTerm; then printf '%s' "$msg" >&2; fi
# write to logfile if enabled and it exists
[ -n "$logPath" ] && [ -f "$logPath" ] && { printf '%s' "$msg" >>"$logPath"; } 2>/dev/null
}
logPath=/path/to/logfile # Enable all logging to file
logTerm=false # Do not copy logging to terminal (stderr)
log + 'Logging is enabled' # Write a message to logfile and terminal
log 'Written to the logfile' # Write a message just to the logfile
who | log # Write a block of text to the terminal
logPath=/path/to/logfile # Enable all logging to file
logTerm=true # Copy all logging to terminal (stderr)
log + 'Logging is enabled' # Write a message to logfile and terminal
log 'Written to the logfile' # Write a message to both the logfile and terminal
who | log # Write a block of text to both the logfile and terminal