Journaux préfixés avec la date dans le script shell
Question
J'ai un script shell avec de nombreuses instructions d'écho. Je souhaite préfixer chaque ligne de sortie avec l'heure / date.
Alors, j'ai remplacé chaque
echo "Some text1"
echo "Some text2"
avec
echo "`date +%y/%m/%d_%H:%M:%S`:: some text1"
echo "`date +%y/%m/%d_%H:%M:%S`:: some text2"
C'est plutôt moche. Y a-t-il quand même pour créer un alias (ou l'analogue à un #define en c), pour le rendre plus propre.
Évidemment, faire quelque chose comme:
DATE=`date +%y/%m/%d_%H:%M:%S`
echo "$DATE:: some text1"
echo "$DATE:: some text2"
... ne fonctionnerait pas, car dans ce cas, la date n'est calculée qu'une seule fois et chaque écho aurait la même date.
Je pense à remplacer chaque écho par un appel de fonction d'impression, qui fait la préfixe. Je veux savoir si quelqu'un a d'autres / meilleures idées.
La solution
echodate()
{
echo `date +%y/%m/%d_%H:%M:%S`:: $*
}
echodate Some text 1
echodate Some text 2
Autres conseils
Si vous utilisez Bash ...:
#!/bin/bash
function myecho() {
echo "`date +%y/%m/%d_%H:%M:%S`:: $@"
}
myecho "hola"
Oui, la fonction du shell ou utilise inversement un alias:
alias now="date +%s" # or your specific date format
echo "`now` some text"
#!/bin/bash
echo() {
printf "`date`: $1\n"
}
echo "test"
--
aura pour résultat:
abi @ cefix: ~ $ sh test.sh
FR 18. Mär 13:33:35 CET 2011: Test
Vous n'avez donc pas à changer toutes vos instructions d'écho.
Or just store the format:
format="+%y/%m/%d_%H:%M:%S::"
echo $(date $format) some text
Not so much quoting is needed, btw.
If you are using KornShell (ksh) here is a function:
#** Description: Logs stringToLog to scriptLog using a standard date format.
#** Parameters: ${1} stringToLog (Required)
#** ${2} scriptLog (Required)
log() {
echo "[`date +'%Y/%m/%d %H:%M:%S%s'`]: ${1}" >> "${2}"
}
Example of calling the above function:
log "Starting foo script." "${PWD}/logs/foo.log"