Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Arguments and String Manipulation  ›  Lesson

String Length and Substrings

String length 12 minParameter expansion can measure a string with ${#var} and cut a piece out with ${var:start:length}, counting positions from zero.

String Length and Substrings

backup.sh has stamp=2026-09-25 and wants a yearly folder: ~/backups/2026/. You could call another program to cut the text, but Bash can do it itself, instantly, with parameter expansion: extra operators inside ${ }.

The rule

${#var} counts; ${var:start:length} slices, counting from zero.

stamp=2026-09-25
echo "${#stamp}"        # 10
echo "${stamp:0:4}"     # 2026   (start at 0, take 4)
echo "${stamp:5:2}"     # 09     (start at 5, take 2)
echo "${stamp:8}"       # 25     (start at 8, take the rest)
echo "${stamp: -2}"     # 25     (last two characters)
  • ${#var} is the number of characters in the value.
  • ${var:start} takes everything from start to the end.
  • ${var:start:length} takes length characters from start.
  • A negative start counts back from the end, but it needs a space (or parentheses) after the colon: ${stamp: -2}.

That space is not decoration. :- without a space is a different operator: ${var:-default} means use the value, or default if the variable is empty or unset. That operator is useful in its own right:

label="${2:-backup}"     # use the second argument, or "backup" if none

For arrays, ${#arr[@]} counts elements, while ${#arr[0]} is the length of the first element.

The shortcut

Write the index line under the string. Put 0 under the first character, then count up. The start is the index under the first character you want; the length is how many you take.

2 0 2 6 - 0 9 - 2 5
0 1 2 3 4 5 6 7 8 9
Getting the month from 2026-09-25Step 1 of 4
  1. Find the first character

    The month's 0 sits under index 5 (the dash before it is 4).

Drills

Answer fast — trust the rule.

quick drill

With stamp=2026-09-25, what is ${#stamp}?

quick drill

With stamp=2026-09-25, what is ${stamp:5:2}?

quick drill

With stamp=2026-09-25, what is ${stamp: -2}?

quick drill

With stamp=2026-09-25, what is ${stamp:-2}?

Remember

  • ${#var} counts; ${var:start:length} slices, counting from zero.
  • Write the index line: the last index is the length minus one.
  • Trap: ${var: -2} needs the space; ${var:-x} is the default-value operator.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainPieces of a date

backup.sh has stamp=2026-09-25. Write expansions that give the length of the stamp, the year, the month and the last two characters, and explain how the positions are counted and why ${stamp:-2} is not the same as ${stamp: -2}.