This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
sage-logger
executable file
·58 lines (50 loc) · 1.54 KB
/
sage-logger
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/env bash
#
# sage-logger [-p] COMMAND LOGFILE
#
# Evaluate shell command COMMAND while logging stdout and stderr to
# LOGFILE. If either the command or the logging failed, return a
# non-zero exit status.
#
# If the -p argument is given, each line printed to stdout is prefixed
# with the name of the log file.
#
# AUTHOR:
#
# - Jeroen Demeyer (2015-07-26): initial version based on old pipestatus
# script (#18953)
#
#*****************************************************************************
# Copyright (C) 2015 Jeroen Demeyer <jdemeyer@cage.ugent.be>
#
# Distributed under the terms of the GNU General Public License (GPL)
# as published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
use_prefix=false
if [[ "$1" = -p ]]; then
use_prefix=true
shift
fi
cmd="$1"
logfile="$2"
logname="$(basename $logfile .log)"
logdir=`dirname "$logfile"`
if [[ $use_prefix = true ]]; then
prefix="[${logname}] "
else
prefix=""
fi
mkdir -p "$logdir"
# Redirect stdout and stderr to a subprocess running tee.
# We trap SIGINT such that SIGINT interrupts the main process being
# run, not the logging.
( exec 2>&1; eval "$cmd" ) | ( trap '' SIGINT; tee -a "$logfile" ) | \
(while read line; do echo "${prefix}${line}"; done)
pipestatus=(${PIPESTATUS[*]})
if [ ${pipestatus[1]} -ne 0 ]; then
exit ${pipestatus[1]}
else
exit ${pipestatus[0]}
fi