How can I count the number of characters in a Bash variable

LinuxBash

Linux Problem Overview


How can I count all characters in a bash variable? For instance, if I had

"stackoverflow"

the result should be

"13"

Linux Solutions


Solution 1 - Linux

Using the ${#VAR} syntax will calculate the number of characters in a variable.

https://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion

Solution 2 - Linux

Use the wc utility with the print the byte counts (-c) option:

$ SO="stackoverflow"
$ echo -n "$SO" | wc -c
    13

You'll have to use the do not output the trailing newline (-n) option for echo. Otherwise, the newline character will also be counted.

Solution 3 - Linux

jcomeau@intrepid:~$ mystring="one two three four five"
jcomeau@intrepid:~$ echo "string length: ${#mystring}"
string length: 23

link https://stackoverflow.com/questions/8736856/bash-script-to-count-word-charcters-in-string

Solution 4 - Linux

${#str_var}  

where str_var is your string.

Solution 5 - Linux

you can use wc to count the number of characters in the file wc -m filename.txt. Hope that help.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionlacrosse1991View Question on Stackoverflow
Solution 1 - LinuxStevePView Answer on Stackoverflow
Solution 2 - LinuxmihaiView Answer on Stackoverflow
Solution 3 - LinuxRajView Answer on Stackoverflow
Solution 4 - LinuxagaView Answer on Stackoverflow
Solution 5 - LinuxNorbert WuponaView Answer on Stackoverflow