0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Find Length of String

In Bash, you can find the length of a string using ${#string}, for example: length=${#mystring} stores the length of mystring in length.
📋

Examples

Inputhello
Output5
InputBash scripting
Output14
Input
Output0
🧠

How to Think About It

To find the length of a string in Bash, think of the string as a sequence of characters. You want to count how many characters it has. Bash provides a simple way to get this count using the ${#string} syntax, which directly returns the number of characters in the string variable.
📐

Algorithm

1
Get the string input or define a string variable.
2
Use the syntax ${#string} to get the length of the string.
3
Store or print the length as needed.
💻

Code

bash
#!/bin/bash
mystring="Hello, world!"
length=${#mystring}
echo "Length of string: $length"
Output
Length of string: 13
🔍

Dry Run

Let's trace the string "Hello, world!" through the code

1

Define string

mystring="Hello, world!"

2

Calculate length

length=${#mystring} = 13

3

Print length

Output: Length of string: 13

VariableValue
mystringHello, world!
length13
💡

Why This Works

Step 1: Use of ${#string}

The ${#string} syntax in Bash returns the number of characters in the variable string.

Step 2: Assign length to variable

We assign this length to a variable like length to use or print it later.

Step 3: Print the result

Using echo, we display the length to the user.

🔄

Alternative Approaches

Using expr command
bash
mystring="Hello"
length=$(expr length "$mystring")
echo "$length"
This uses an external command and is less efficient than built-in syntax.
Using wc command
bash
mystring="Hello"
length=$(echo -n "$mystring" | wc -c)
echo "$length"
This counts bytes via wc, useful if you want to handle input from echo, but slower than built-in.

Complexity: O(1) time, O(1) space

Time Complexity

Getting the length with ${#string} is a constant time operation because Bash stores string length metadata.

Space Complexity

No extra memory is needed beyond the input string and a variable to store the length.

Which Approach is Fastest?

Using ${#string} is fastest as it is built-in; external commands like expr or wc add overhead.

ApproachTimeSpaceBest For
${#string}O(1)O(1)Simple and fast length retrieval
expr lengthO(n)O(1)Legacy scripts or compatibility
echo + wc -cO(n)O(1)Counting bytes from output streams
💡
Use ${#string} for the fastest and simplest way to get string length in Bash.
⚠️
Forgetting to use quotes around the string variable can cause errors or unexpected results.