I am trying to write a function in bash that takes a Linux command and runs it sending output to a log file. For each line the command outputs I want to add date/time in front of it in the log file. I almost got it working but some Linux commands don't work.
Code:
function log {
timestamp=`date +%D_%R`
log_text="${timestamp} $1"
printf "${log_text}\n" >> $LOG
}
function log_file {
while read line
do
log "${line}"
done < "$1"
}
function run_cmd {
tmp_log=/tmp/$$_cmd.log
log "$1"
$1 > ${tmp_log} 2>&1
ret=$?
if [ -f ${tmp_log} ]; then
log_file ${tmp_log}
fi
if [ ${ret} -ne 0 ]; then
log "${ret} : $1"
fi
return ${ret}
}
This works most of the time, for example if I do
run_cmd "ls -l /tmp"
The log file has each line of the output from ls on a separate line of the logfile with date/time before it.
However, if I do
du -hc --time --max-depth=1 /home/back/tvpp/ | sort -k2
I get the following (error)
03/26/19_19:03 du -hc --time --max-depth=1 /home/back/tvpp/ | sort -k2
03/26/19_19:03
du: invalid option -- '2'
03/26/19_19:03
Try 'du --help' for more information.
03/26/19_19:03
1 : du -hc --time --max-depth=1 /home/back/tvpp/ | sort -k2
Its something to do with using pipes but can quite figure it out.