如何在 bash 脚本中使用包含带空格的文件名的变量?

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

How do I use a variable containing a filename with spaces in a bash script?

bashfilenamesspacescp

提问by nick

I have a simple bash script running on OS X that removes specific files and directories and copies new ones in their place. One Mac .app directory contains a space, and when I run the script there is a "No such file or directory" error.

我有一个在 OS X 上运行的简单 bash 脚本,它删除特定的文件和目录并将新的文件和目录复制到它们的位置。一个 Mac .app 目录包含一个空格,当我运行脚本时出现“没有这样的文件或目录”错误。

Here is the relevant code. A good amount has been cut out, so simply hard coding these differently isn't possible (the variables must be broken up as they are):

这是相关的代码。大量已被删减,因此不可能简单地对这些进行硬编码(变量必须按原样分解):

CP="cp -Rf"

INSTALL_DIR="/Applications/"

APP="The App.app"

NEWAPP="$HOME/Downloads/The App.app"

$CP "$NEWAPP " "$INSTALL_DIR$NEWAPP"

I've tried escaping The\ App.appwith no luck, as well as trying single quoting, double quoting, and double escaping, but nothing has worked. I imagine there is a simple way to do this.

我尝试过The\ App.app没有运气的转义,以及尝试单引号、双引号和双转义,但没有任何效果。我想有一种简单的方法可以做到这一点。

Thanks for your help.

谢谢你的帮助。

回答by Karoly Horvath

You have an extra space there, it's simply

你有一个额外的空间,它只是

"$NEWAPP"

“$NEWAPP”

回答by emergence

enclose the whole final line in quotes:

用引号将整个最后一行括起来:

"$CP $NEWAPP $INSTALL_DIR$NEWAPP"

it's unnecessary to keep opening and closing the quotes here, and the $CP must be contained in quotes as CP has a space in it.

没有必要在这里继续打开和关闭引号,并且 $CP 必须包含在引号中,因为 CP 中有一个空格。