Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you take a suffix of a string in bash using negative offsets?

Tags:

bash

shell

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"?

like image 910
qntm Avatar asked Jul 17 '15 13:07

qntm


1 Answers

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}
like image 171
jvdm Avatar answered Sep 30 '22 20:09

jvdm