简体   繁体   English

$ {MYPATH //://:// bin:} / bin在bash shell中是什么意思?

[英]what does ${MYPATH//://bin:}/bin mean in bash shell?

I've been seeing a case of appending a particular dir named 'bin' under $MYPATH (which could contain multiple values in format of a:b:c ) to $PATH , the solution is ${MYPATH//://bin:}/bin ,for example: 我一直在看到在$MYPATH下附加一个名为'bin'的特定目录(该目录可能包含a:b:c格式的多个值)到$PATH ,解决方法是${MYPATH//://bin:}/bin ,例如:

> MYPATH=/local/a:/local/b
> echo ${MYPATH//://bin:}/bin
/local/a/bin:/local/b/bin
> echo ${MYPATH}/bin  # as a bad example, this is not what we want
/local/a:/local/b/bin

as you see, ${MYPATH//://bin:}/bin works pretty well. 如您所见, ${MYPATH//://bin:}/bin效果很好。

My question is where is such parameter expansion documented, I can't find any doc(include 'man bash', seems it's not the "Substring Expansion" which in format of {parameter:offset:length} ) on explaining the syntax. 我的问题是在哪里记录了此类参数扩展,我在解释语法时找不到任何文档(包括“ man bash”,似乎不是“子字符串扩展”,其格式为{parameter:offset:length} )。

Could anyone explain it to me or point me the doc of this feature? 谁能向我解释一下或给我指出此功能的文档?

This is called Parameter expansion. 这称为参数扩展。 In this case, it replaces all : with /bin: 在这种情况下,它将所有:替换为/bin:

${MYPATH//://bin:}
  ^^^^^^  ^ 
   |    ^^| ^^^^^
   |    | | replacement
   |    | match string
   var  match all

Too many slashes are misleading. 太多的斜杠具有误导性。 See better examples: 查看更好的例子:

MYPATH="hello1hello2"
$ echo ${MYPATH//hello/bye}
bye1bye2

or: 要么:

d="a:b:c"
$ echo ${d//://bin:}
a/bin:b/bin:c

Note the difference if we just use one slash: 请注意,如果我们仅使用一个斜杠,则会有所不同:

$ echo ${MYPATH/hello/bye}
bye1hello2

More info in Parameter expansion#Search and replace . 参数扩展#Search and replace中的更多信息。

Substring Expansion 子串扩展

This is a confusing, although valid, implementation of the substring expansion form of: 这是以下内容的子串扩展形式的一种实现方法,尽管有效,但令人困惑:

${parameter//pattern/string}

The doubled forward slash will replace all copies of pattern of with string , rather than just the first match. 加倍的正斜杠将用string代替所有pattern模式的副本,而不仅仅是第一个匹配项。 In your example: 在您的示例中:

echo ${MYPATH//://bin:}/bin

the expansion says: 扩展说明:

  1. Match all copies of pattern : . 匹配模式的所有副本:
  2. Replace each match with the string /bin: . 将每个匹配项替换为字符串/bin:
  3. Append a literal /bin to the result of the substring expansion, since it's outside the parameter expansion. 在子字符串扩展的结果后附加文字/bin ,因为它在参数扩展之外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM