Bash by Example: String Length
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
# character inside the braces tells Bash to return the length of the variable's value instead of the value itself.-gt stands for "greater than".empty_var="" initializes an empty string variable.${#empty_var} returns 0 for an empty string.
