I am trying to understand a test script, which includes the following segment:
我正在尝试理解一个测试脚本,它包括以下部分:
SCRIPT_PATH=${0%/*}
if [ "$0" != "$SCRIPT_PATH" ] && [ "$SCRIPT_PATH" != "" ]; then
cd $SCRIPT_PATH
fi
What does the ${0%/*}
stand for? Thanks
${0%/*}代表什么?谢谢
1 个解决方案
#1
66
It is called Parameter Expansion
. Take a look at this page and the rest of the site.
它被称为参数展开。看看这个页面和网站的其他部分。
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, $0
is the same as ${0}
which is like any other argument, eg. $1
which you can write as ${1}
. As I said $0
is special, as it's not a real argument, 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:
%/*匹配/并删除该字符后的任何(*表示任何)内容。看看这个简单的例子:
$ var="foo/bar/baz"
$ echo "$var"
foo/bar/baz
$ echo "${var}"
foo/bar/baz
$ echo "${var%/*}"
foo/bar
#1
66
It is called Parameter Expansion
. Take a look at this page and the rest of the site.
它被称为参数展开。看看这个页面和网站的其他部分。
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, $0
is the same as ${0}
which is like any other argument, eg. $1
which you can write as ${1}
. As I said $0
is special, as it's not a real argument, 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:
%/*匹配/并删除该字符后的任何(*表示任何)内容。看看这个简单的例子:
$ var="foo/bar/baz"
$ echo "$var"
foo/bar/baz
$ echo "${var}"
foo/bar/baz
$ echo "${var%/*}"
foo/bar