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

≯℡__Kan透↙ 提交于 2019-12-02 04:43:06

问题


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.

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.app with 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.

Thanks for your help.


回答1:


You have an extra space there, it's simply

"$NEWAPP"




回答2:


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.



来源:https://stackoverflow.com/questions/6848783/how-do-i-use-a-variable-containing-a-filename-with-spaces-in-a-bash-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!