为什么Bash字符串下标中的空格在这里很重要?

时间:2017-12-08 13:19:29

标签: linux bash

我正在尝试使用bash脚本并注意到以下行为:

Test

实际上非常混乱的行为。有人可以解释为什么第二种情况打印整个file="test.jar" echo "${file: -4}" #prints .jar echo "${file:-4}" #prints test.jar

2 个答案:

答案 0 :(得分:3)

这是由于语法不一致造成的。 ArrayList<String>表示默认(所有字符串),无论{"string":-}后面是什么。所以你需要一个空格或括号:

-

阅读bash string manipulation

答案 1 :(得分:1)

由于功能的时间线被添加到Bash,这是一种妥协。

  • ${parameter:-word} ${parameter-word} parameterword语法,如果 {{ 1}} 为空或未设置(parameter)/ null(:-)“几乎总是存在; -版本已在Version 7 Bourne Shell
  • - 的子字符串的${parameter:offset:length}${parameter:offset}语法,从 parameter 开始(可选长度) offset )“是在Bash 2.0中引入的(到目前为止没有冲突)。
  • Bash 4.2中引入了子串构造的负偏移和长度规范。这导致了一个问题:

    length

$ string=01234567890abcdefgh $ echo ${string:7:-2} # Not ambiguous 7890abcdef $ echo ${string:-7} # Interpreted as "undefined/null, or..." 01234567890abcdefgh $ echo ${string: -7} # Interpreted as offset from the end bcdefgh $ echo ${string:(-7)} # Interpreted as offset from the end bcdefgh 之前的空格或负偏移量周围的括号表示扩展区别于-(默认值)扩展。

如果空格不存在,如果参数:-为空或未设置,则展开${file:-4}将被解释为“打印4,否则会扩展file

参考文献: