bash BASH中“${1#*-}”是什么意思

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41806725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:38:46  来源:igfitidea点击:

What is the meaning of "${1#*-}" in BASH

bash

提问by rɑ?d?ɑ

There is a if condition as below

有一个 if 条件如下

if [ "${1#*-}" = "" ]; then
   echo "Do something"
fi

But could somebody explain what is the meaning of ${1#*-}?

但是有人能解释一下是什么意思${1#*-}吗?

回答by Kent

${1#*-}deletes the shortest match of *-, a glob-like pattern from $1variable.

${1#*-}*-$1变量中删除 的最短匹配项,一个类似 glob 的模式。

E.g. abcdef-xyz-foo-> xyz-foo

例如abcdef-xyz-foo->xyz-foo

Your ifcheck does actually:

您的if支票实际上是:

if  does not contain '-'

回答by chepner

*-is a pattern matching a (possibly empty) string followed by a -. The #operator drops the shortestprefix matching *-from the expansion of $1. An example:

*-是一个匹配(可能为空)字符串后跟一个的模式-。该#运营商下降到最短前缀匹配*-,从扩张$1。一个例子:

$ foo="123-456"
$ echo "${foo#*-}"
456
$ foo="123-456-789"
456-789

I emphasize shortest because there is a companion operator ##that drops the longestmatching prefix.

我强调最短是因为有一个伴随运算符##丢弃最长的匹配前缀。

$ echo "${foo##*-}"
789

回答by Jhonatan

This test if no have "-"in a parameter 1

此测试是否"-"在参数 1 中没有

See this:

看到这个:

test=jhonatan
if [ "${test#*-}" = "$test" ]; then 
    echo "yes" ; 
else 
    echo "no" ;
fi

This print yes because no have "-"in a string test

这个打印是因为"-"在字符串测试中没有

with this

有了这个

test=jhonatan-piffer

The same script print no.

相同的脚本打印没有。

${variable#pattern}remove prefix pattern of string.

${variable#pattern}删除字符串的前缀模式。

In this last case all string between start until "-"

在最后一种情况下,开始到之间的所有字符串 "-"

echo ${test#*-}

result in:

导致:

"piffer"

and "piffer"differs from "jhonatan-piffer"

并且"piffer"不同于"jhonatan-piffer"

Read this for more information: https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion

阅读更多信息:https: //www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion