How to append Timestamp to file name in Shell script
Contents
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
1 2 |
curr_dt=`date +"%Y-%m-%d-%H-%M-%S"` log_file=script_name.$curr_dt.log |
Example Script to append timestamp to filename
1 2 3 4 5 6 |
$cat hello.sh #!/usr/bin/bash curr_dt=`date +"%Y-%m-%d-%H-%M-%S"` log_file=`basename $0 sh`$curr_dt.log echo "hello world" |tee -a $log_file |
- 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).
Recommended Articles