Prefix logs with date in shell script

I have a shell script with many echo expressions. I want to prefix each line of output with time and date.

So, I replaced every

echo "Some text1"
echo "Some text2"

from

echo "`date +%y/%m/%d_%H:%M:%S`:: some text1"
echo "`date +%y/%m/%d_%H:%M:%S`:: some text2"

This is pretty ugly. Do I need to create an alias (or C # define analog in C) to make it cleaner.

Obviously something like:

DATE=`date +%y/%m/%d_%H:%M:%S`
echo "$DATE:: some text1"
echo "$DATE:: some text2"

... will not work, because in this case, DATE is calculated only once, and each echo has the same date.

I am thinking of replacing each echo with a call to the print function, which makes a prefix. I want to know if anyone has any other / better ideas.

+5
source share
6 answers
echodate()
{
    echo `date +%y/%m/%d_%H:%M:%S`:: $*
}

echodate Some text 1
echodate Some text 2
+12
source

If you use bash ...:

#!/bin/bash

function myecho() {
        echo "`date +%y/%m/%d_%H:%M:%S`:: $@"
}

myecho "hola"
+4
source

, :

alias now="date +%s" # or your specific date format
echo "`now` some text"
+3
#!/bin/bash
echo() {
    printf "`date`: $1\n"
}

echo "test"

-

:

abi @cefix: ~ $sh test.sh

Fr 18. Mär 13:33:35 CET 2011:

-.

+3

Or just save the format:

format="+%y/%m/%d_%H:%M:%S::"
echo $(date $format) some text

It doesn’t need a lot of quoting, by the way.

+1
source

If you are using KornShell (ksh), there is a function here:

#** 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}"
}

An example of calling the specified function:

log "Starting foo script." "${PWD}/logs/foo.log"
-1
source

All Articles