我试图使用${string:pos} substring语法在
Bash中使用字符串的后缀,但是我无法弄清楚为什么它不起作用.我已经设法简化了我的示例代码:
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"@H_403_3@前三行完全按照我的预期,但为什么最后一行打印“你好世界”而不是“orld”?
因为: – 是参数扩展语法为“使用默认值”.
@H_403_3@从documentation:
STRING,如果未设置(从未分配过)或为null
(一个空字符串,打印为”),它将替换为
在您的示例中,STRING已设置,因此将其扩展为其值. @H_403_3@正如另一个答案所说,你需要把表情看成没有
触发默认值行为,手册指定:
@H_403_3@When not performing substring expansion,using the form described@H_403_3@所以通过${STRING:-4}你实际上是要求bash来扩展
below (e.g.,‘:-’),Bash tests for a parameter that is unset or
null.
STRING,如果未设置(从未分配过)或为null
(一个空字符串,打印为”),它将替换为
在您的示例中,STRING已设置,因此将其扩展为其值. @H_403_3@正如另一个答案所说,你需要把表情看成没有
触发默认值行为,手册指定:
@H_403_3@Note that a negative offset must be separated from the colon by at@H_403_3@例如:
least one space to avoid being confused with the :- expansion.
${STRING:(-4)} ${STRING: -4}