0
0
Bash Scriptingscripting~5 mins

String length (${#var}) in Bash Scripting

Choose your learning style9 modes available
Introduction
You use ${#var} to find out how many characters are in a string. This helps when you want to check or use the length of text in your script.
Checking if a user input is empty or too long.
Counting characters in a filename before processing it.
Validating password length in a script.
Measuring the length of a string read from a file.
Controlling loops based on string length.
Syntax
Bash Scripting
length=${#variable}
Replace 'variable' with your string variable name.
The result is the number of characters in the string, including spaces.
Examples
Counts the characters in the string 'hello' and prints 5.
Bash Scripting
name="hello"
len=${#name}
echo $len
Shows that an empty string has length 0.
Bash Scripting
empty=""
len=${#empty}
echo $len
Counts characters including the space, prints 11.
Bash Scripting
text="hello world"
len=${#text}
echo $len
Sample Program
This script sets a string, calculates its length, and prints the result.
Bash Scripting
#!/bin/bash

input="Bash scripting"
length=${#input}
echo "The length of '$input' is $length."
OutputSuccess
Important Notes
Spaces and special characters count as one character each.
If the variable is unset, length is zero.
This method works only for simple strings, not arrays.
Summary
Use ${#var} to get the number of characters in a string.
It counts all characters including spaces.
Useful for input validation and string processing.