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}.
name="hello" length=${#name} echo $length
| Step | Variable | Action | Value | Output |
|---|---|---|---|---|
| 1 | name | Assign 'hello' | hello | |
| 2 | length | Calculate ${#name} | 5 | |
| 3 | echo $length | Print length | 5 | 5 |
| Variable | Start | After 1 | After 2 | Final |
|---|---|---|---|---|
| name | hello | hello | hello | |
| length | 5 | 5 |
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.${#var} do in a bash script?${#var}var.name in bash?${#variable}, so for name it is ${#name}.text="Hello World"
echo ${#text}echo ${#text} prints the length, which is 11.myvar=Hello length=$#myvar echo $length
$# returns the number of positional parameters passed to the script, not the length of a string variable.length=$#myvar tries to get positional parameters count, ignoring myvar. So it does not get string length.input is empty or not in a bash script. Which condition correctly uses string length to do this?${#input}.[ ${#input} -eq 0 ] correctly tests if the string length is zero.Pass the test and this pattern moves unknown