0
0
Bash Scriptingscripting~10 mins

String length (${#var}) in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - String length (${#var})
Start with variable
Apply ${#var}
Calculate length
Return length as number
Use or display length
This flow shows how bash calculates the length of a string stored in a variable using ${#var}.
Execution Sample
Bash Scripting
name="hello"
length=${#name}
echo $length
This script stores 'hello' in name, calculates its length, and prints it.
Execution Table
StepVariableActionValueOutput
1nameAssign 'hello'hello
2lengthCalculate ${#name}5
3echo $lengthPrint length55
💡 Script ends after printing the length 5.
Variable Tracker
VariableStartAfter 1After 2Final
namehellohellohello
length55
Key Moments - 2 Insights
Why does ${#name} give 5 instead of the string itself?
Because ${#name} returns the number of characters in the string stored in name, not the string content itself. See execution_table step 2.
What happens if the variable is empty or unset?
If the variable is empty or unset, ${#var} returns 0, meaning the string length is zero. This is shown by the initial empty state in variable_tracker.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'length' after step 2?
A5
Bhello
C0
D${#name}
💡 Hint
Check the 'Value' column in row for step 2 in execution_table.
At which step is the string length printed to the screen?
AStep 1
BStep 2
CStep 3
DNo step prints output
💡 Hint
Look for the 'Output' column showing printed value in execution_table.
If name was empty, what would ${#name} return?
AAn error
B0
CEmpty string
D1
💡 Hint
Refer to key_moments about empty or unset variable behavior.
Concept Snapshot
Use ${#var} to get the length of the string in var.
It returns the number of characters as a number.
If var is empty or unset, length is 0.
Example: name="hi"; echo ${#name} outputs 2.
Full Transcript
This lesson shows how to find the length of a string in bash using ${#var}. First, assign a string to a variable. Then use ${#var} to get its length as a number. Finally, print or use that number. If the variable is empty, the length is zero. The example uses name="hello" and prints 5 because hello has 5 letters.