MenuMenuCoursesTutorialsGlossaryCommandsLinux BasicsBash ScriptingUbuntuNetworkingBash ProgrammingLinux ApplicationsMiscellaneousCheat SheetsForumAbout HomeHomeHome > > Bash Scripting TutorialBash Scripting TutorialBash Scripting Tutorial > > Bash StringBash StringBash String > > Bash String OperationsBash String OperationsBash String Operations > > How to Find Length of String..." /> MenuMenuCoursesTutorialsGlossaryCommandsLinux BasicsBash ScriptingUbuntuNetworkingBash ProgrammingLinux ApplicationsMiscellaneousCheat SheetsForumAbout HomeHomeHome > > Bash Scripting TutorialBash Scripting TutorialBash Scripting Tutorial > > Bash StringBash StringBash String > > Bash String OperationsBash String OperationsBash String Operations > > How to Find Length of String..." /> How to Find Length of String in Bash [6 Methods] - LinuxSimply

How to Find Length of String in Bash [6 Methods]

The length of a string refers to finding the number of characters in a string. It is essential to find length for text processing, input validation, and parse text. The basic syntax to find the length of a string is the ${#string}. The syntax is straightforward and does not require any external command to find the length.

Let’s take a look at different methods to find the length of a string.

6 Ways to Find the Length of a String

Besides the basic syntax hash(#)with curly brackets, there are some other commands like the wc command, awk command, and expr command used to find the length of a string. In this part, I will show 6 methods to find the length of a string in bash.

1. Using Parameter Expansion With “#”

Parameter expansion refers to the process of manipulating and expanding the values of the variable. Using this # symbol with the parameter expansion, you can get the length of the given variable’s value. Generally, the hash(#) symbol is used for commenting, but it is also used as a variable substitution and special parameter in bash.

To know the length of a string, go through the following code:

#!/bin/bash

String="Hello, World!"
length=${#String}

echo "The length of the string is: $length"
EXPLANATION

The string has been declared in a variable string. Then the length of the string is stored in the length variable. The#in the${#String}calculates the length of the following string variable.