Recall & Review
beginner
What does the syntax
${var:offset:length} do in bash scripting?It extracts a substring from the variable
var, starting at position offset and taking length characters.Click to reveal answer
beginner
If
var="hello world", what is the result of ${var:6:5}?The substring starting at position 6 with length 5 is
world.Click to reveal answer
intermediate
What happens if the
length in ${var:offset:length} is omitted?The substring will include all characters from
offset to the end of the string.Click to reveal answer
intermediate
Can the
offset be negative in ${var:offset:length}? What does it mean?Yes, a negative
offset counts from the end of the string backwards. For example, ${var: -3} starts 3 characters from the end.Click to reveal answer
beginner
How would you extract the first 4 characters of a variable
var in bash?Use
${var:0:4} to get the first 4 characters starting at position 0.Click to reveal answer
What does
${var:3:2} extract from var="abcdefg"?✗ Incorrect
Starting at position 3 (0-based), the substring is "de".
If
var="hello", what does ${var:1} return?✗ Incorrect
Without length, it returns substring from offset 1 to end: "ello".
What happens if
offset is negative in ${var:offset:length}?✗ Incorrect
Negative offset counts backwards from the end of the string.
Which command extracts the first 3 characters of
var?✗ Incorrect
Start at 0, take 3 characters extracts the first 3 characters.
If
var="bash scripting", what does ${var:5} return?✗ Incorrect
Offset 5 means start at 6th character to end, which is "scripting".
Explain how to extract a substring from a bash variable using the syntax ${var:offset:length}. Include what happens if length is omitted or offset is negative.
Think about how you cut a piece from a string, starting point and size.
You got /5 concepts.
Describe a real-life example where substring extraction in bash scripting can be useful.
Imagine you have a filename and want just the extension.
You got /4 concepts.