Created
August 17, 2024 14:43
-
-
Save drblue/80152e41ff44c8cf621789fcae8fe562 to your computer and use it in GitHub Desktop.
Log output of a command to both a file and the console.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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