Bash Find
In this topic, we have demonstrated about finding the length of a string in Bash Scripting.
The total number of characters in any string indicates the length of a string. In some cases, we might need to know about the length of a string to perform some specific tasks. Most of the programming languages have their own built-in functions to calculate the number of characters. However, Bash does not contain such type of built-in functions. But there are several ways that we can use to find the length of a string in Bash Scripting.
Bash StringLength
To calculate the length of a string, we can use any of the following syntax:
Note: Observe the double quotes used around $string. If a string has spaces in it, then double quotes are very important. Otherwise, it can be ignored. We recommend to always use double quotes around $string to be on the safe side.
The above syntax defines that we can find the length of a string with or without bash command. Using ‘#’ sign, we can calculate the length of a string without applying any bash command. Let’s understand it more clearly with the help of some examples:
Examples to find String Length in Bash
There are some examples given below illustrating the different ways to find a string length in bash shell scripting:
Example 1
The simplest way to calculate the length of a string is to use ‘#’ symbol. In this example, we have used $[#string_variable_name} to find the length of a string.
Bash Script
Output
Length of 'Welcome to Tutor Aspire' is 21
Example 2
Another way to calculate the length of a string is to use `expr` command with the ‘length’ keyword. In this example, we have used `expr length “$str”` to find the length of a string.
Bash Script
Output
Length of 'Welcome to Tutor Aspire' is 21
Example 3
In this example, we have used `expr “$str”: ‘ .*’`to find the length of a string. Here, str is a string variable.
Bash Script
Output
Length of 'Welcome to Tutor Aspire' is 21
Example 4
In this example, we have used `wc` command to find the length of a string.
Bash Script
Output
Length of 'Welcome to Tutor Aspire' is 22
Example 5
In this example, we have used `awk` command to find the length of a string.
Bash Script
Output
Length of 'Welcome to Tutor Aspire' is 21
Conclusion
In this topic, we have learned about the syntax to find the length of a string with the examples.