bash中的"cd $ {0%/*}"是什么意思? [英] What does 'cd ${0%/*}' mean in bash?

查看:918
本文介绍了bash中的"cd $ {0%/*}"是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了 git commit ,它清除了一些readlinkdirname命令,并使用此魔术变量替换cd ${0%/*}.

I encountered a git commit which cleans up some readlink and dirname command with this magic variable substitution cd ${0%/*}.

bash如何解释它?

How does bash interpret it?

推荐答案

此处的%称为模式匹配运算符.

The % here is called pattern-matching operator.

学习Bash Shell 书中的引言:

模式匹配运算符的经典用法是剥离路径名的组件,例如目录前缀和文件名后缀.考虑到这一点,下面的示例显示了所有操作员的工作方式.假设变量path的值为/home/cam/book/long.file.name;然后:

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:

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.

在您的特定情况下,在我的示例中,0path是对等的,因此您应该知道它.

In your specific case, 0 is the counterpart of the path in my example, so you should know it.

如果$0/home/chj/myfile.txt,则cd ${0%/*}将扩展为cd /home/chj,即剥离文件"部分.

If $0 is /home/chj/myfile.txt , cd ${0%/*} will expand to be cd /home/chj, i.e. stripping of the "file" part.

我理解您提出这个问题的冲动,因为要在不花几个小时的时间阅读一本Bash书的情况下,很难找到答案.

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中的"cd $ {0%/*}"是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆