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


i trying take suffix of string in bash using ${string:pos} substring syntax, cannot figure out why won't work. have managed simplify example code 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 3 lines work expect, why final line print "hello world" instead of "orld"?

because :- parameter expansion syntax "use default values".

from documentation:

when not performing substring expansion, using form described below (e.g., ‘:-’), bash tests parameter unset or null.

so doing ${string:-4} asking bash expand string , if unset (have never been assigned before) or null (a null string, printed '') substitute expansion 4. in example, string set , expanded value.

as answer states, need scape expression not trigger default value behavior, manual specifies it:

note negative offset must separated colon @ least 1 space avoid being confused :- expansion.

for example:

${string:(-4)} ${string: -4} 

Comments