I am trying to take the suffix of a string in Bash using the ${string:pos}
substring syntax, but I cannot figure out why it won't work. I have managed to simplify my example code to this:
STRING="hello world"
POS=4
echo ${STRING:POS} # prints "o world"
echo ${STRING:4} # prints "o world"
POS=-4
echo ${STRING:POS} # prints "orld"
echo ${STRING:-4} # prints "hello world"
The first three lines work exactly as I would expect, but why does the final line print "hello world"
instead of "orld"
?
Because :-
is parameter expansion syntax to "Use default values".
From the documentation:
When not performing substring expansion, using the form described below (e.g., ‘:-’), Bash tests for a parameter that is unset or null.
So by doing ${STRING:-4}
you are actually asking bash to expand
STRING
and if it is unset (have never been assigned before) or null
(a null string, printed as ''
) it will substitute the expansion with
4
. In your example, STRING
is set and thus it is expanded to its value.
As another answer states, you need to scape the expression to not trigger the default value behavior, the manual specifies it:
Note that a negative offset must be separated from the colon by at least one space to avoid being confused with the :- expansion.
For example:
${STRING:(-4)}
${STRING: -4}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With