Skip to content

Instantly share code, notes, and snippets.

@tkurtbond
Created July 9, 2021 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkurtbond/23255fede737eec89b1fd0e011566cb1 to your computer and use it in GitHub Desktop.
Save tkurtbond/23255fede737eec89b1fd0e011566cb1 to your computer and use it in GitHub Desktop.
bash functions for logging the output of long commands run multiple times
incf () {
# Construct a filename from PREFIX, "_YYYY-MM-DD", optionally _N (where N
# is 1 or greater) if the filename already exists, and optionally SUFFIX.
# Example: "incf file .tar.gz" results in "file_2021-07-07.tar.gz", or
# "file_2021-07-07_N.tar.gz" if "file_2021-07-07.tar.gz" already exists,
# where N is 1 or greater.
local prefix suffix fileprefix i testname sep1 sep2
prefix="$1"
suffix="$2"
sep1="_"
sep2="_"
fileprefix="${prefix}${sep1}$(date +%F)"
let i=0
# The zeroth filename doesn't have the number.
testname="${fileprefix}${suffix}"
while true
do
[ ! -e "$testname" ] && break
((i++))
testname="${fileprefix}${sep2}${i}${suffix}"
done
echo "$testname"
}
logf () {
# Construct a filename, possibly in another directory, that starts with
# "Log." and ends with "YYYY-MM-DD" and optionally "_N", where N is 1 or
# greater, if the filename already exists.
local dn bn fn
dn="$(dirname "$1")"
bn="Log.$(basename "$1")"
fn="$(incf "$dn/$bn")"
echo $fn
}
log () {
# tee the input into a log file.
tee $(logf "$1")
}
cleanname () {
# Clean up a string so it is (relatively) safe to use as a filename.
local cmd="$*" name
name=$(echo "$cmd" | sed 's/[ =";?*&^%$#@!~`|()<>]/-/g' | \
sed "s#[/']#-#g" | sed -E 's/--+/-/g' | \
sed -E 's/(^[-.]+|-+$)//g' | \
sed -E 's/\.\.\.*/./g')
echo "$name"
}
exlog () {
# Execute a shell command and log it to "Log.<cmd-as-safe-filename>"
local cmd="$*" name="$(cleanname "$@")"
name="$(logf $name)"
printf 'Logging to %s\n' "$name"
(echo "cmd was: $cmd"; time "$@") 2>&1 | tee $name
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment