Reputation: 18191
I have a shell script with a lot of echo statements. I want to prefix each line of output with the time/date.
So, I replaced every
echo "Some text1"
echo "Some text2"
with
echo "`date +%y/%m/%d_%H:%M:%S`:: some text1"
echo "`date +%y/%m/%d_%H:%M:%S`:: some text2"
This is rather ugly. Is there anyway to create an alias (or the analog to a #define in C), to make it cleaner.
Obviously, doing something like:
DATE=`date +%y/%m/%d_%H:%M:%S`
echo "$DATE:: some text1"
echo "$DATE:: some text2"
... would not work, because in that case the DATE is only calculated once and each echo would have the same date.
I am thinking about replacing every echo with a print function call, that does the prefixing. I want to know if anyone has any other/better ideas.
Upvotes: 12
Views: 16520
Reputation: 4963
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"
Upvotes: -1
Reputation: 36229
Or just store the format:
format="+%y/%m/%d_%H:%M:%S::"
echo $(date $format) some text
Not so much quoting is needed, btw.
Upvotes: 2
Reputation: 41
#!/bin/bash
echo() {
printf "`date`: $1\n"
}
echo "test"
--
will result in:
abi@cefix:~$ sh test.sh
Fr 18. Mär 13:33:35 CET 2011: test
so you dont have to change all your echo statements.
Upvotes: 4
Reputation: 10637
Yes, shell function or conversely use an alias:
alias now="date +%s" # or your specific date format
echo "`now` some text"
Upvotes: 3
Reputation: 21175
If you're using bash...:
#!/bin/bash
function myecho() {
echo "`date +%y/%m/%d_%H:%M:%S`:: $@"
}
myecho "hola"
Upvotes: 4
Reputation: 118605
echodate()
{
echo `date +%y/%m/%d_%H:%M:%S`:: $*
}
echodate Some text 1
echodate Some text 2
Upvotes: 21