'cd ${0%/*}' 在 bash 中是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28894290/
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
What does 'cd ${0%/*}' mean in bash?
提问by steveyang
I encountered a git commitwhich cleans up some readlink
and dirname
command with this magic variable substitution cd ${0%/*}
.
我遇到了一个git commit,它用这个神奇的变量替换清理了一些readlink
和dirname
命令cd ${0%/*}
。
How does bash interpret it?
bash 如何解释它?
回答by Jimm Chen
The %
here is called pattern-matching operator.
在%
这里被称为模式匹配操作。
A quote from Learning the Bash Shellbook:
引自《学习 Bash Shell》一书:
The classic use for pattern-matching operators is in stripping off components of pathnames, such as directory prefixes and filename suffixes. With that in mind, here is an example that shows how all of the operators work. Assume that the variable path
has the value /home/cam/book/long.file.name
; then:
模式匹配运算符的经典用途是剥离路径名的组成部分,例如目录前缀和文件名后缀。考虑到这一点,以下示例展示了所有运算符的工作方式。假设变量path
的值为/home/cam/book/long.file.name
;然后:
Expression Result Comments
${path##/*/} long.file.name ## takes out longest matched substring from the front
${path#/*/} cam/book/long.file.name # takes out shortest matched substring from the front
$path /home/cam/book/long.file.name
${path%.*} /home/cam/book/long.file % takes out shortest matched substring from the rear
${path%%.*} /home/cam/book/long %% takes out longest matched substring from the rear
These can be hard to remember, so here's a handy mnemonic device:
这些可能很难记住,所以这里有一个方便的助记符:
#
matches the front because number signs precede numbers;%
matches the rear because percent signs follow numbers.
#
匹配前面,因为数字符号在数字之前;%
匹配后面,因为百分号跟在数字后面。
In your specific case, 0
is the counterpart of the path
in my example, so you should know it.
在您的特定情况下,0
是path
我示例中的对应物,因此您应该知道它。
If $0
is /home/chj/myfile.txt
, cd ${0%/*}
will expand to be cd /home/chj
, i.e. stripping of the "file" part.
如果$0
是/home/chj/myfile.txt
,cd ${0%/*}
将扩展为cd /home/chj
,即剥离“文件”部分。
I understand your urge to ask this question, because it is too hard to search for the answer without several hours digging into a Bash book.
我理解您提出这个问题的冲动,因为如果不花几个小时深入研究 Bash 书籍,就很难找到答案。
回答by Ross Ridge
The command cd ${0%/*}
changes directory to the directory containing the script, assuming that $0
is set to the fully-qualified path of the script.
该命令cd ${0%/*}
将目录更改为包含脚本的目录,假设该目录$0
设置为脚本的完全限定路径。