Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differentiate between 2 and 02 in bash script

I have a bash script that takes the date, month and year as separate arguments. Using that, a url is constructed which then uses wget to fetch content and store it in an html file (say t.html). Now, the user may enter a 2 digit month/date (as in 02 instead of just 2 and vice-versa). How do I distinguish between the above two formats and correct for this from within the script?

The url works as follows:
Date: a 2 digit input is needed. So a 7 must be supplied as 07 for the url to be constructed properly. Here I am looking for a check that would append a zero to the date in case it is less than 10 and does not already have a zero in front. So, 7 should become 07 for the date field before the url is constructed.
Month: a 2 digit input is needed, but here the url automatically appends the 0 in case month < 10. So, if the user enters 2, then the url forms 02, but if the user enters 02, the url forms 002. Here, the 0 may need to be appended or removed.

P.S: I know this method followed by the url s*c&s, but I just need to work with it.

Thanks,
Sriram

like image 766
Sriram Avatar asked Apr 08 '26 00:04

Sriram


1 Answers

It's a little unclear what you're asking for. If you're only looking to strip one leading zero, then this will do:

month=${month#0}

This will turn 02 into 2, and 12 remains 12.

If you need to remove more than one zero (above 002 will turn into 02), you'll need to do something different, like using regular expressions

while [ -z "${month##0*}" ]; do month=${month#0}; done

or use regular expressions, like with sed

month=$(sed -e 's/^0*//'<<<"$month")

HTH

EDIT
As per your edit; as has already been suggested, use printf

month=$(printf %02d "$month")

this will turn 2 into 02, 12 remains as is, as does 123. If you want to force a two digit number or you don't have printf (which is a shell built-in in bash, and usually available otherwise too, so chances are pretty low), sed can help again

month=$(sed -e 's/.*\(..\)$/\1/'<<<"00$month")

which will prepend two zeros (002) and keep the last two characters (02), turning the empty string into 00 as well. This will turn a into 0a too though. Come to think of it, you don't need sed for this

month="00$month"
month="${month:0-2}"

(The 0- is required to disambiguate from default value expansion)

like image 89
falstro Avatar answered Apr 10 '26 22:04

falstro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!