Bash Parameter Substrings and Length
Parameter substrings take part of a value by position. Length counts the characters in the whole value.
Take a slice by offset and length
Offset 0 is the first character. Four characters from 0 give Bash, and three from 4 give Scr.
word="BashScript"
echo "${word:0:4}"
echo "${word:4}"
echo "${word:4:3}"Count back from the end
A negative offset counts back from the last character. The space before the minus keeps it apart from the :- default form.
word="BashScript"
echo "${word: -6}"
echo "${word: -3}"
echo "${word: -3:2}"Measure a value with #
The # form counts characters, not words. BashScript has ten characters, and an empty value has zero.
word="BashScript"
empty=""
echo "${#word}"
echo "${#empty}"Example
code="USR-4821-ACTIVE"
echo "Code: $code"
echo "Prefix: ${code:0:3}"
echo "Number: ${code:4:4}"
echo "Status: ${code: -6}"
echo "Length: ${#code}"Key points
- ${var:offset:length}: take length characters starting at offset.
- ${var:offset}: take everything from offset to the end.
- Offsets count from zero, so 0 is the first character.
- A negative offset counts back from the end, with a space before the minus.
- ${#var}: count the characters in var.
- An empty value has length zero.
In this example, the code holds a prefix, a number, and a status joined by dashes. Offset 0 takes the three-letter prefix. Offset 4 takes the four-digit number. A negative offset of six takes the status from the end. The # form counts all fifteen characters.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
For word=BashScript, what does ${word:4:3} give?