BudiBadu Logo
Samplebadu

Bash by Example: String Length

Bash 5.0+

How to get the length of a string variable using the ${#var} parameter expansion syntax, understanding that this counts bytes not characters for multi-byte encodings, using string length in conditional tests for validation, implementing input validation by checking minimum and maximum lengths, and leveraging this for string manipulation operations.

Code

#!/bin/bash

text="The quick brown fox"

# Get string length
length=${#text}

echo "String: '$text'"
echo "Length: $length"

# Conditional check based on length
if [ ${#text} -gt 10 ]; then
    echo "The string is long."
fi

# Empty string check
empty_var=""
echo "Empty length: ${#empty_var}"

Explanation

To find the length of a string stored in a variable, Bash provides the parameter expansion syntax ${#variable}. This returns the number of characters in the string.

This operation is efficient and built directly into the shell, so it doesn't require spawning external processes like wc -c or awk. It works correctly with spaces and special characters.

This syntax is commonly used in validation logic, such as checking if a password meets a minimum length requirement or if an input field is empty. It is much faster than piping data to other commands.

Code Breakdown

6
The # character inside the braces tells Bash to return the length of the variable's value instead of the value itself.
12
Using the length directly in a conditional expression. -gt stands for "greater than".
17
empty_var="" initializes an empty string variable.
18
${#empty_var} returns 0 for an empty string.