bash 脚本中的 ${0%/*} 是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6393551/
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-09 20:40:07  来源:igfitidea点击:

What is the meaning of ${0%/*} in a bash script?

bashscripting

提问by user785099

I am trying to understand a test script, which includes the following segment:

我正在尝试理解一个测试脚本,其中包括以下部分:

SCRIPT_PATH=${0%/*}
if [ "
$ var="foo/bar/baz"
$ echo "$var"
foo/bar/baz
$ echo "${var}"
foo/bar/baz
$ echo "${var%/*}"
foo/bar
" != "$SCRIPT_PATH" ] && [ "$SCRIPT_PATH" != "" ]; then cd $SCRIPT_PATH fi

What does the ${0%/*}stand for? Thanks

代表什么${0%/*}?谢谢

回答by c00kiemon5ter

It is called Parameter Expansion. Take a look at this pageand the rest of the site.

它被称为Parameter Expansion。看看这个页面和网站的其余部分。

What ${0%/*}does is, it expands the value contained within the argument 0(which is the path that called the script) after removing the string /*suffix from the end of it.

什么${0%/*}是,它在从它的末尾删除字符串后缀后扩展包含在参数 0(这是调用脚本的路径)中/*的值。

So, $0is the same as ${0}which is like any other argument, eg. $1which you can write as ${1}. As I said $0is special, as it's not a realargument, it's always there and represents name of script. Parameter Expansion works within the {}-- curly braces, and %is one type of Parameter Expansion.

所以,$0是一样的${0}是像任何其他说法,如。$1你可以写成${1}. 正如我所说$0,它很特别,因为它不是真正的参数,它始终存在并代表脚本名称。参数扩展在{}-- 花括号内工作,%是参数扩展的一种。

%/*matches the last occurrence of /and removes anything (*means anything) after that character. Take a look at this simple example:

%/*匹配最后一次出现/并删除*该字符之后的任何内容(意味着任何内容)。看看这个简单的例子:

##代码##