Skip to content

Instantly share code, notes, and snippets.

@drblue
Created August 17, 2024 14:43
Show Gist options
  • Save drblue/80152e41ff44c8cf621789fcae8fe562 to your computer and use it in GitHub Desktop.
Save drblue/80152e41ff44c8cf621789fcae8fe562 to your computer and use it in GitHub Desktop.
Log output of a command to both a file and the console.
#!/bin/bash
# Function to show usage
usage() {
echo "logf: A script to execute a command and log its output to both a file and the console."
echo
echo "Usage: $0 [-a] <logfile> <command> [args...]"
echo " -a Append to the logfile instead of overwriting"
exit 1
}
# Check if there are at least two arguments
if [ "$#" -lt 2 ]; then
usage
fi
# Check for the -a option
APPEND=false
if [ "$1" == "-a" ]; then
APPEND=true
shift
# Check again if there are at least two arguments after shifting
if [ "$#" -lt 2 ]; then
usage
fi
fi
# Extract the logfile parameter
LOGFILE=$1
shift
# Set the tee command based on the append option
if $APPEND; then
TEE_CMD="tee -a"
else
TEE_CMD="tee"
fi
# Execute the command and log output to both the logfile and the console
"$@" 2>&1 | $TEE_CMD "$LOGFILE"
# Exit with the command's exit code
exit ${PIPESTATUS[0]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment