Agregar marca de tiempo a las entradas del registro de secuencias de comandos

Agregar marca de tiempo a las entradas del registro de secuencias de comandos

Actualmente uso mi script bash exec 22>&2 21>&1 1>$log 2>&1para escribir stderr y stdout en un archivo de registro. Me gustaría agregar una marca de tiempo para cada entrada, pero no he encontrado una manera fácil de hacerlo. Lo ideal sería un simple cambio en el comando actual con la hora escrita en la misma línea antes que el resto.

Aquí hay un script en el que estoy usando el comando:

#!/bin/bash

#This script takes the server to rysnc as an argument. You can also tell 
#the script to check the server_status.txt file.
#
#Example: /path/to/script/sync.sh grail true
#
#The arguments are order senstive. The server name must come before the status
#check value.

#Logfile
LOG=/var/log/sync.log

DIRECTORYS="auth/ keys/ log/mailwhen/ intranet/ www/calmaa/data/ www/admatch/data/ www/sfhsa/data/ www/hfa3_org www/padmatch/ www/serverdown/"

if [ "x$2" == "xfalse" ]; then
    return 0
elif [ "x$2" == "xtrue" ]; then
    if [ `cat /srv/www/wan*/server_status.txt` == "primary" ]; then
        exit 0
    fi
else
    echo "Please use \"true\" or \"false\" for the second value." 
    exit 1
fi

# Copy stdout and stderr, and then open the logfile
exec 22>&2 21>&1 1>$log 2>&1
# Here is how to restore stdout and stderr:
# exec 2>&22 1>&21

for DIRECTORY in $DIRECTORYS; do
    rsync -azu --delete --bwlimit=500 $1:/srv/$DIRECTORY  /srv/$DIRECTORY
done

Respuesta1

Sin ver más de su guión, no puedo decirle cuál es la mejor manera para sus necesidades particulares. Sin embargo, esta es una forma general que puede adaptarse a sus necesidades.

exec > >(while read -r line; do printf '%s %s\n' "$(date --rfc-3339=seconds)" "$line"; done)

Cada línea de texto que se genere tendrá la marca de tiempo del momento en que ocurrió antepuesta. La salida se verá así:

2013-09-04 21:32:14-05:00 An event occurred and this is the message
2013-09-04 21:32:37-05:00 Some time passed, another event produced a message

Respuesta2

editar secuencia con sed:

sed "s/^/$(date -u) /"

usando tubería:

[root@giomacdesk ~]# cat test.txt 
asd1
asd2
[root@giomacdesk ~]# cat test.txt |sed "s/^/$(date -u) /"
ოთხ სექ  4 19:00:53 UTC 2013 asd1
ოთხ სექ  4 19:00:53 UTC 2013 asd2
[root@giomacdesk ~]# 

información relacionada