Parameter Expansion for Length/Substring
In this page:
Getting String Length with ${#s}
${#s} expands to the number of characters currently stored in the variable s, which is the standard length-checking idiom in Bash. It counts characters, not bytes, in a locale-aware way for most standard configurations.
Example: Getting String Length with ${#s}
#!/bin/bash
word="Bash"
echo "The word '$word' has ${#word} characters"
Login to try C/C++/Java/PHP code in the editor
Extracting a Substring with ${s:pos:len}
${s:pos:len} extracts len characters from s starting at zero-based index pos. This is a purely Bash built-in operation, requiring no external tools like cut or awk.
Example: Extracting a Substring with ${s:pos:len}
#!/bin/bash
sentence="The quick brown fox"
word=${sentence:4:5}
echo "Extracted word: $word"
Login to try C/C++/Java/PHP code in the editor
Omitting the Length
Leaving out the length argument, ${s:pos}, extracts everything from index pos all the way to the end of the string. This is convenient when you don't know or don't care exactly how long the remaining text is.
Example: Omitting the Length
#!/bin/bash
path="/usr/local/bin/mytool"
remainder=${path:5}
echo "Everything after index 5: $remainder"
Login to try C/C++/Java/PHP code in the editor
Negative Starting Position
A negative pos, written with a leading space like ${s: -4}, counts backward from the end of the string instead of from the beginning. This is a quick way to grab the last few characters of a string, such as a file extension.
Warning: ${filename:-4} (no space) would instead trigger the default-value expansion, not a substring extraction.
Example: Negative Starting Position
#!/bin/bash
filename="report_final.txt"
last_four=${filename: -4}
echo "Last four characters: $last_four"
Login to try C/C++/Java/PHP code in the editor
- Confusing
${#s}(length of the strings) with${#arr[@]}(length of an array); the#prefix means 'length of' in both cases, but what follows determines whether it's a string or array count. - Assuming
${s:pos:len}uses one-based indexing like some other tools; Bash string indexing is zero-based, so${s:0:1}is the first character. - Forgetting that a negative starting position needs a space before the minus sign (
${s: -3}) to avoid being parsed as the${var:-default}expansion instead of a substring extraction.
${#s}gives the number of characters in the strings.${s:pos:len}extractslencharacters starting at zero-based positionpos.- Omitting
lenin${s:pos}extracts everything fromposto the end of the string. - A negative
poscounts backward from the end of the string, but requires a leading space or parentheses to avoid ambiguity with:-.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: