#!/bin/sh set -ue # Wrapper for logging to file and prepending a timestamp. # By default writes both stdout and stderr to the log file. usage() { echo "Usage: logto [-s|-e] " echo "Flags:" echo " -s: Write only stdout to the log file." echo " -e: Write only stderr to the log file." echo "" echo "Example usage:" echo " logto /var/log/my.log run some command" exit 1 } mode="all" while getopts "se" opt; do case $opt in s) mode="stdout" ;; e) mode="stderr" ;; *) usage ;; esac done shift $((OPTIND-1)) if [ $# -lt 2 ]; then usage fi log_file="$1" shift if [ "$mode" = "stdout" ]; then out=$(2>/dev/null $@) elif [ "$mode" = "stderr" ]; then out=$(2>&1 >/dev/null $@) else out=$(2>&1 $@) fi if [ ! -z "$out" ]; then echo "$(date +"%Y-%m-%dT%H:%M:%S%z")" "$out" >>"$log_file" fi