The date command is a strangely useful tool. It is most commonly used to create timestamps, particularly when logging events that have happened. The syslog utility adds timestamps to events that it logs, so /var/log/messages, syslog, auth.log, and other such files all contain that key ingredient at the start of the line. This can be vital for working out the chain of events and how different events captured in different log files, or even on different machines, tie in with each other.

Typical Uses of date

The two most common uses of the date command in system administration are probably logging results and status messages, particularly when logging to a file, and creating temporary files with meaningful names. Scripts for both of these techniques are provided here, followed by some of the more complex things made possible by the advanced features of the date command. This first recipe emulates the logger facility described later in this chapter. The second uses the date to create a set of uniquely but informatively named log files. In this example, the timestamp is useful for tracking down the error in the web server. A common NTP source is also particularly useful, although even totally independent systems can be compared if the time difference between them can be established.

cat #!/bin/bash LOG=/var/tmp/uptime.log echo "'date': Starting the $0 script." | tee -a $LOG ...

Get Shell Scripting: Expert Recipes for Linux, Bash, and More now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.