Lets start a very Basic, yet powerful Language Tutorial. The Bash Scripting. Basically it is acronym of "The Bourne Again Shell". Today, I am going to discuss some Basics by considering following scenario.
Let's assume that you need to do some task for range of dates or over a period of dates. So here there will be a Start Date & End Date. Also it would be great if you can give this range of dates to your script at the command line so no need to edit the script every time. when I said command line it means that one can give argument at the time of execution of the bash script.
Summary of scenario,
1. Script should accept Date range as command line arguments.
2. Date must be in YYYYMMDD Format.
Now, let's talk about the actual code.
Following is the sample code of the implementation. You can also get it from my GitHub repository.
#!/bin/bash # This code takes Date as input in YYYYMMDD Format. StartDate=`date +"%Y%m%d" -d $1` #"20160601"` EndDate=`date +"%Y%m%d" -d $2` #"20160605"` if [ $# -ne 2 ] then echo "Usage:`basename $0` Start_Date End_Date" echo "bash `basename $0` 20160601 20160605" exit $E_BADARGS fi echo "StartDate: "$StartDate echo "EndDate: "$EndDate while [ "$StartDate" -le "$EndDate" ] ; do echo $StartDate #Print the Date in YYYYMMDD Format # Increment Date by one day StartDate=`date +"%Y%m%d" -d "$StartDate + 1 day"`; done echo "All Done"
Above code has one "IF" & one "WHILE" loop. "StartDate" & "EndDate" both are variables and indicates the starting date and end date respectively. I have used "date" command with user specified format for the date. I have used "YYYYMMDD" format for date by specifying "+"%Y%m%d"" to date command. To take First command line argument as input one need to use "$1"; for second argument "$2" and so on.
Next is the IF loop. It checks the count of command line arguments. "$#" gives count of command line arguments in Bash. The WHILE loop simply iterates starting from "StartDate" to "EndDate" and print the current value of "StartDate" variable. To increment date by one we again use "date" command. For example purpose I am just printing the value of the StartDate but one can use their own task to get work done.
A sample command to run the above programme would be like as follows.
$ bash CopyFilesDateAsInput.bash 20160101 20161231
Following is the sample output of the script for quick reference.
$bash CopyFilesDateAsInput.bash 20160101 20160103 StartDate: 20160101 EndDate: 20160103 20150601 20150602 20150603 All Done
I hope you understood the discussion so far and liked the post. This was a very short post to get start but in future we will discuss more lengthy and complex codes.
I would like to Thank You for visiting the Website & going through the post. Stay tuned for more interesting stuff.
==>Posted By Yogesh B. Desai
Next Post: BASH Script: Copy Files From Source To Destination Within Given Date Range.
Previous Post: LINUX Home Page.