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 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.
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 9Find the first character
The month's
0sits under index 5 (the dash before it is 4).
Drills
Answer fast — trust the rule.
With stamp=2026-09-25, what is ${#stamp}?
With stamp=2026-09-25, what is ${stamp:5:2}?
With stamp=2026-09-25, what is ${stamp: -2}?
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.
