Create file with TimeStamp in Shell Script

I love using Ubuntu OS for development. I need to create a shell script that saves new file with a timestamp. Following are steps that I’ve followed:

Understanding date command.

nishant@nishantvaity:~$ date
Wed Sep 18 13:53:49 IST 2019

Use any of following command to know options for date command.

nishant@nishantvaity:~$ date --h

OR

nishant@nishantvaity:~$ man date
NAME
date -- display or set date and time
SYNOPSIS
date [-ju] [-r seconds] [-v [+|-]val[ymwdHMS]] ... [+output_fmt]
date [-jnu] [[[mm]dd]HH]MM[[cc]yy][.ss]
date [-jnu] -f input_fmt new_date [+output_fmt]
date [-d dst] [-t minutes_west]

Display date on Terminal

nishant@nishantvaity:~$ date +"%Y/%m/%d"
2019/09/18

Display date with timestamp

nishant@nishantvaity:~$ echo $(date "+%Y.%m.%d_%H.%M.%S")
2019.09.18_14.02.43

Create a shell script that saves new file with a timestamp.

#!/bin/sh
file_name="my_file_name_here_"
current_time=$(date "+%Y.%m.%d_%H.%M.%S")
file_extension=".txt"
new_fileName=$file_name$current_time$file_extension
echo "Content here that goes to file" > $new_fileName
echo "Some more content to append" >> $new_fileName

Nishant Vaity

Knowledgeable and skilled Technology Lead with an ability of software development and supervision. Possess a Bachelor of Science (BS) in Information Technology along with 11+ years of experience with hands-on coding and team management. By profession, I am a Software Engineer, Technology Mentor & Entrepreneur. Passionate about the technologies I use and always eager to share & learn more from that passion.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.