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 fromstartto the end.${var:start:length}takeslengthcharacters fromstart.- 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 noneFor arrays, ${#arr[@]} counts elements, while ${#arr[0]} is the length of the first element.