Create time stamp based file to store information using shell scripting
As an administrator or GNU/Linux enthusiast you might come across a requirement of logging information from you shell scripts into files whenever they are run. We would love to do this if the files created have a unique name and also give out information when it was created.
In this post we will see how we can achieve that.
How to create a unique file name
The best way to create a unique file name would be to use the current UNIX timestamp also to be doubly sure you could add some extra string to your filename to avoid mix up with some other application trying to do the same (Though this can be a very rare thing)
So how do we get this time stamp string
The date command in GNU/Linux not only can be used to just display date but can be use to set date and many other things. One of the useful things that it can do for us is generate the time stamp or generate a date string as per our requirement.
running the following command: date "+%s" will give us the current timestamp which will be something like 1589718363.
Thought this will be unique does not help much in recognizing the file name easily. (though there are ways to convert this information)
So we will format our date string in a better manner i.e. Year Month Day Hours Minutes and Seconds
we will use the following command: date "+%Y%m%d%H%M%S" where you can now guess what the characters represent. This will give us an output something like this 20200517180729 i.e 2020 year, 05 month, 17 day, 18 hour, 07 minute, 29 second.
Now to use this for a filename we need to store it into a variable i.e.
FileDateName=`date "+%Y%m%d%H%M%S"` (note the back ticks are used and not single quotes)
This way we have file name ready, next to create this file, to do so we run it with touch command
Now your file is ready. According to your requirements add/append using redirection to this file.
Lets say I want to store the memory usage into the above file whenever it run the script, This can be achieved by the free command, the command when used with the -mw give the following output
total used free shared buffers cache available Mem: 5837 2493 933 560 119 2291 2526 Swap: 17597 252 17345
From above we need to store the total, used and free info say. So we can will filter 2nd line and cut the 2nd 3rd and 4th col. we will process the above command as
free -mw | head -n2 | tr -s ' ' | cut -d' ' -f2,3,4 // this will give the give the following output
total used free
5837 2539 1062
Now let put this into a script
# create file name
# create the actual empty file
# run command for required info and redirect this to the created file.
free -mw | head -n2 | tr -s ' ' | cut -d' ' -f2,3,4 > $FileDateName
That is it. simple