Length and substring expansion
How it works
${#text} returns the length of a scalar string in characters under the current locale. ${text:offset:length} selects a portion beginning at zero-based offset; without length it continues to the end. Offset and length are arithmetic expressions: use trusted numbers, not raw user text. A negative offset counts from the end. Insert a space after the colon in ${text: -3} so Bash does not interpret :- as a default. A negative length marks an end position relative to the end of the string for ordinary scalars; it is not a negative character count. If that end lies before the start, Bash reports a substring expression error. The offset rules for positional parameters and arrays differ; use these examples only for scalar strings. This lesson uses ASCII in the C locale; character counts in other locales need not equal bytes or displayed grapheme clusters.
Run each example separately in a noninteractive Bash 5.2 script in a fresh empty practice directory, with default options and C locale. Output is shown separately; do not enter it as code.
Length and first characters
Expected stdout:
6repIndex zero is the first character.
From the end
Expected stdout:
ortreportThe space makes the negative offset unambiguous.
Omitted and negative length
text=abcdefprintf '%s' "${text:2}" "${text:1:-2}" "$text"Expected stdout:
cdefbcdabcdefThe second slice starts at b and ends before e; text stays intact.
Common mistakes
${text:-3} is a fallback expression, not a slice. Substring syntax is Bash-specific for this track; do not assume it works in sh. Extracting a string does not change it.
Practice
Given code=AB-2048, print its length, the first two characters and the last four characters without external commands.
Next: Remove prefixes and suffixes