Length of string in bash

AJP picture AJP · Jun 28, 2013 · Viewed 562k times · Source

How do you get the length of a string stored in a variable and assign that to another variable?

myvar="some string"
echo ${#myvar}  
# 11

How do you set another variable to the output 11?

Answer

fedorqui 'SO stop harming' picture fedorqui 'SO stop harming' · Jun 28, 2013

To get the length of a string stored in a variable, say:

myvar="some string"
size=${#myvar} 

To confirm it was properly saved, echo it:

$ echo "$size"
11