The length of a string is determined by the number of characters it contains, and it is generally straightforward to ascertain this length for normal text.

This post will explore various methods for counting the number of characters in a string with UTF encoding.

  1. Using ${#variable} Syntax

The first method involves utilizing the ${#variable} syntax to obtain the length of a string variable.

In this, number of characters in the string variable.

msg="Hello World."
count=${#msg}

echo $count # 12

Output:

12
  1. Using wc -m Command

The second method involves the use of the wc -m command, either directly with a string or through a variable.

echo -n 'Hello World.' | wc -m; # 12

result=`echo -n $msg | wc -m`
echo $result # 12

result1=`echo  $msg | wc -m`
echo $result1 # 12

In this example, echo -n "string" is employed to print the string without a new line (-n option). The | pipe operator directs the output of the left-side command to the right-side command, and wc -m counts the number of characters in a string.

Output:

12
12
12
  1. Using the expr Command Another method involves using the expr command to find the length of a string.

msg="Hello World."

count=$(expr length "$msg")

echo $count # 12

Here, ${} represents expression substitution, substituting the value of an expression into the string. expr executes expressions, and length is an argument passed to expr to find the string’s length.

$(expr length "$msg") returns the count of a characters in a string, assigned to an variable, variable value printed to console

  • using awk command Awk provides yet another way to calculate the length of a string using expressions.
msg="Hello World."
count=${#msg}

echo $count # 12

count=$(echo -n "$msg" | awk '{print length}')
echo $count # 12

In this case, echo -n "$variable" outputs the string without a new line, and the output is piped to awk using the pipe(|) symbol. The awk '{print length}' command calculates and prints the length of the input line.

By combining the above methods in an expression ${}, you can obtain the length of a string.

Conclusion

This post has covered multiple ways to determine the length of a string in Bash. The choice of approach can depend on your preferences.