I have a following simple extract from my script which is strangely stuck up for a particular inputs.
echo -e "Enter the Day of the Month : \c "
read input_day
printf -v input_day '%02d' "$input_day"
This makes sure that if the user inputs a single digit number e.g. 2 then it converts it to 02. Which is my first requirement. This also works if one enters 2 digits number as 02. Then it retains it as 02. This also works for a 2 digit number as 12. But strangely it fails to accept the digit 08 and 09? This is the error it gives when one enters 08 or 09.
Enter the Day of the Month : 08
2: line 20: printf: 08: invalid number
Why is it so? I tried to read printf help page and it shows that "d" stands for Signed decimal integer. So it should accept the digits 8 and 9. Or am I missing something? My requirement is that user should be able to enter the day of the month as single digit "8" as well as double digit "08".
1 Answer 1
bash
will interpret a number with a leading zero as octal. The format is not the problem, the $input_day
variable is the problem.
You can remove those with a variety of methods (see for example awk equivalent of LTRIM function in C ).
Further reading:
Removing leading zeros before passing the variable to iptables
uses this syntax:$((10#$machinenumber))
, e.g., for your example:printf -v input_day '%02d' "$((10#$input_day))"
Bash: Removing leading zeroes from a variable
is more to the point:shopt -s extglob printf -v input_day '%02d' ${input_day##+(0)}
By the way, the example does not check if the variable is empty. But validating that properly would be another question.
-
I referred to the post you suggested. But could not figure out how to implement here. You mean to replace $input_day with awk ??Sachin H– Sachin H2016年03月08日 10:15:47 +00:00Commented Mar 8, 2016 at 10:15
-
Hello, printf -v input_day '%02d' "$((10#$input_day))" works neat!!!Sachin H– Sachin H2016年03月08日 12:29:55 +00:00Commented Mar 8, 2016 at 12:29
$(( 10#$input_day ))
to convert your input to base 10