← Back to Bash Course | Chapter 7: String Manipulation | Lesson 1 of 10

Parameter Expansion for Length/Substring

Bash can tell you how many characters are in a string and pull out any smaller piece of it, all without calling an external program.

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}

bash
#!/bin/bash
word="Bash"
echo "The word '$word' has ${#word} characters"

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}

bash
#!/bin/bash
sentence="The quick brown fox"
word=${sentence:4:5}
echo "Extracted word: $word"

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

bash
#!/bin/bash
path="/usr/local/bin/mytool"
remainder=${path:5}
echo "Everything after index 5: $remainder"

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

bash
#!/bin/bash
filename="report_final.txt"
last_four=${filename: -4}
echo "Last four characters: $last_four"
Common Mistakes
  1. Confusing ${#s} (length of the string s) 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.
  2. 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.
  3. 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.
Chapter Summary
  • ${#s} gives the number of characters in the string s.
  • ${s:pos:len} extracts len characters starting at zero-based position pos.
  • Omitting len in ${s:pos} extracts everything from pos to the end of the string.
  • A negative pos counts backward from the end of the string, but requires a leading space or parentheses to avoid ambiguity with :-.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.