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".

  • a number which starts with '0' is an octal number. Octal digits can reach from 0 to 7. Therefore 08 and 09 are invalid numbers
    – syss
    Mar 8 '16 at 10:17
  • You can force conversion to different base. Use the following $(( 10#$input_day )) to convert your input to base 10
    – bsd
    Mar 8 '16 at 10:21

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:

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
    Mar 8 '16 at 10:15
  • Hello, printf -v input_day '%02d' "$((10#$input_day))" works neat!!!
    – Sachin H
    Mar 8 '16 at 12:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.