Shell Script - Date/Time
Hi,
In shell scripting how would I add the date/time to a log file? Cheers Paul |
Do you mean 'add' as 'append the date at the end of a log file'?
If that is so, do that: Quote:
|
If you want to put the date in the log filename, use command substitution. For example
Code:
command >> /path/to/$(date +%Y%m%d)_file.log |
Also take a look at 'date' command's man page:
Code:
man date Notice the '+FORMAT' there? See the lower part of the man page for formatting strings and combine them into the command to be able to append the date/time in the format you want/need (the default format given by plain 'date' might not be what you want). That method, redirecting the output of a command to a file using '>>', is fairly common and works in DOS too, exactly the same way (except that there might not be 'date' command available). Two greater than -chars ('>>') means 'append' while one ('>') alone clears the file contents before writing the new content, so be aware: Code:
date >> file.log #existing content remains, date is added to the end Code:
man bash Code:
#!/bin/bash |
I usually write a function for writing to log files, something like this:
Code:
#!/bin/bash Code:
20080819-17:09:49 myscript : starting script |
Hi I tried the following:
Code:
#!/sbin/sh - Code:
$(date +%Y%m%d-%T) |
I can think of two possible reasons:
|
From your sha-bang it seems you're using the Bourne shell, where the syntax $(command) for command substitution is not recognized, since it is specific to bash. Use back ticks instead:
Code:
/usr/bin/echo "`date +%Y%m%d-%T` $1" >> ${LOGFILE} |
For the record, both backtick execution
Code:
`command` Code:
$(command) In all these shells you can also use the `backtick` notation. I prefer not to instruct people using backticks for two reasons:
|
I would add that the syntax $(command) interprets the double backslash correctly, or at least in the way you expect it, as an escaped backslash.
|
All times are GMT -5. The time now is 06:22 AM. |