Search code examples
bashshelldigits

Count the number of digits in a bash variable


I have a number num=010. I would like to count the number of digits contained in this number. If the number of digits is above a certain number, I would like to do some processing.

In the above example, the number of digits is 3.

Thanks!


Solution

  • Assuming the variable only contains digits then the shell already does what you want here with the length Shell Parameter Expansion.

    $ var=012
    $ echo "${#var}"
    3