Count the number of digits in a bash variable

activelearner picture activelearner · Jul 9, 2015 · Viewed 19.6k times · Source

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!

Answer

Etan Reisner picture Etan Reisner · Jul 9, 2015

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