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
?
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
?
I was trying to do something similar, but I just wanted to make sure the user input wasn't too long.
UTF-8 string length
In addition to fedorqui's correct answer, I would like to show the difference between string length and byte length:
will render:
you could even have a look at stored chars:
will answer:
Nota: According to Isabell Cowan's comment, I've added setting to
$LC_ALL
along with$LANG
.Length of an argument
Argument work same as regular variables
will work as
Useful
printf
correction tool:If you:
Not really pretty... For this, there is a little function:
Then now:
To get the length of a string stored in a variable, say:
To confirm it was properly saved,
echo
it:If you want to use this with command line or function arguments, make sure you use
size=${#1}
instead ofsize=${#$1}
. The second one may be more instinctual but is incorrect syntax.In response to the post starting:
with the code:
There might be the case where you just want to check for a zero length argument and have no need to store a variable. I believe you can use this sort of syntax:
See GNU and wooledge for a more complete list of Bash conditional expressions.
Here is couple of ways to calculate length of variable :
and to set the result in another variable just assign above command with back quote into another variable as following:
http://techopsbook.blogspot.in/2017/09/how-to-find-length-of-string-variable.html