Bash路径问题
我有一个包含以下行的脚本:
propFile="${0%/*}/anteater.properties"
- “${0%/*}”是什么意思?
- 该命令给出了脚本的路径 - 但路径中有空格,脚本找不到该文件 - 如何处理?
I have a script which contains the following line:
propFile="${0%/*}/anteater.properties"
- What does "${0%/*}" mean?
- This command gives a path to the script - but there is a spaces at path and script can't find this file - how to deal with it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
变量扩展中的
%
运算符会删除为其指定的匹配后缀模式。因此${0%/*}
接受变量$0
,并删除末尾所有匹配的/*
。这相当于命令dirname
,当给出该命令时路径,返回该路径的父目录。为了处理 bash 变量中的空格,每当扩展变量时(即每当你写
$var
时),你应该引用它。简而言之,始终使用"$var"
而不仅仅是$var
。考虑阅读 shell 参数扩展 和 变量引用 了解有关这两个主题的更多信息。
The
%
operator in variable expansion removes the matching suffix pattern given to it. So${0%/*}
takes the variable$0
, and removes all matching/*
at the end. This is equivalent to the commanddirname
, which, when given a path, returns the parent directory of that path.In order to deal with spaces in bash variable, whenever expanding the variable (i.e. whenever you write
$var
), you should quote it. In short, always use"$var"
instead of just$var
.Consider reading shell parameter expansion and variable quoting in the bash manual to learn more about these two subjects.
删除匹配
/*
的后缀,即最后一个斜杠之后的所有内容,包括斜杠本身。无论您使用什么地方都引用它 (
cat "$propFile"
)。strips the suffix matching
/*
, i.e. everything after last slash including the slash itself.quote it wherever you use it (
cat "$propFile"
).