How to append Timestamp to file name in Shell script

Create log file with current timestamp in Bash

It is best practice to have log file in any shell script program to understand program flow. Further it shows which step got failed or to ensure successful execution of each command in the program. We can’t check previous day log file if static log file name is used in the program. So, we should create log file name by static name that suffixed with current timestamp to preserve history of log files.

Syntax to append timestamp to filename

Example Script to append timestamp to filename

  • date means current server date with time
  • %Y means current year in yyyy format
  • %m means current month in mm format
  • %d means current day in dd format
  • %H means current hour in 24 hour format
  • %M means current minute in mm format
  • %S means current second in ss format
  • Dash(-) is separator between each field
  • Back tick(`) is used to execute the command and result will be assigned to curr_dt variable
  • $0 holds script name
  • basename command strips directory path from script name and sh from script name
  • tee will allow echo output is displayed in screen and logged in log file as well
  • -a option will ensure echo output is appended to log file. 

Output of the script

Here hello.sh is the script name that created the log file with the time stamp as hello.2019-07-03-09-23-01.log (<script_name>.<timestamp>.log).

Append timestamp to filename in Shell script
Append timestamp to filename in shell script

Recommended Articles