How to find the length of a string in Bash [Совет]

If you are dealing with strings in bash, you may need to know the length of the string.

Fortunately, getting the length of a string is very easy in bash. Let’s say you have a string named my_string. Its length can be extracted as:

${#my_string}

Here’s an example to better explain:

[email protected]:~$ my_string="destroyer"
[email protected]:~$ echo "длина ${#my_string}"
длина 9

It was easy, right? You can store this string length in another variable and use it later:

[email protected]:~$ my_string="destroyer"
[email protected]:~$ length=${#my_string}
[email protected]:~$ echo "Длина строки $length"
Длина строки 9

Like most other things in Linux, this is not the only way to calculate line lengths in Bash.

Get length of line in bash using expr command

Let’s take a look at some other commands that can help you check line length in bash.

One of these commands is the expr command. It has several options that are useful for string options. Among them length, you get the length of the string.

[email protected]:~$ expr length "моя строка"
10

Since the expr command prints the length, you must store it in a variable using command substitution.

#!/bin/bash

str="моя строка"
length=$(expr length "$str")
echo "Длина моей строки $length"

Now if you run this bash shell script it will print the length:

[email protected]:~$ bash string.sh 
Длина моей строки 10

Use awk to get line length

AWK is a versatile command for editing text on the Linux command line. You can also use it to calculate string length.

You will need to use echo command and then use pipe redirection to parse it with awk command:

[email protected]:~$ echo "моя строка" | awk '{print length}'
10

As you can see, remembering the syntax is not easy if you are not familiar with the basics of working with awk commands.

Using wc command to calculate string length

Another way to get the length of a line on Linux is to use the wc command. Now the wc command is used to count the number of lines, characters in the file.

You can repeat the line and pass it to the wc command. The -m option gives the number of characters.

[email protected]:~$ echo -n "моя строка" | wc -m
10

Notice the -n option with the echo command? This is important because echo automatically adds a new line character n to the end and increases the length of the line by one. With the -n option, the echo command does not add a new lowercase character.

You can use command substitution to store the length of a string in a variable, as you saw in the previous examples.

#!/bin/bash

str="моя строка"
length=$(echo -n "моя строка" | wc -m)
echo "Длина моей строки $length"

We personally prefer $ {# string} to get the length of the string. Easier to remember.

What about you? Which method do you prefer?

Sidebar