Skip to the workspace
Pebellslearn by building
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.

shell bash / String Length and Substrings

Explore each scene at your own pace.

01 · The rule

The rule

String Length and Substrings

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

Measure a value and select a substring with deliberate boundaries.

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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.