简体   繁体   中英

MacOS bash script not honoring double quotes

I have a build script in which I'm trying to copy a file into a directory with spaces. My code works fine when the line is written as such:

cp test.png My\ Program.app/Contents/Resources

but when it's instead written as:

cp test.png “My Program.app/Contents/Resources”

...it fails with an error:

usage: cp [-R [-H | -L | -P]] [-fi | -n] [-apvXc] source_file target_file
       cp [-R [-H | -L | -P]] [-fi | -n] [-apvXc] source_file ... target_directory

What's wrong?

Adding set -x at the beginning of the script helped me see what was happening and identify the problem.

The problem was that there were spaces in the app bundle name (eg "My Program"), and enclosing the path in single or double quotes didn't work -- because the text editor I was using changed double quotes into smart quotes .

What also worked was escaping the spaces with a backslash , like this:


GOOD:

cp -f myfile My\ Program.app/Contents/Resources

GOOD (but be careful; some MacOS text editors may change this to the later, BAD form automatically):

cp -f myfile "My Program.app/Contents/Resources"

BAD (due to the quotes being "smart quotes" instead of plain ASCII quotes):

cp -f myfile “My Program.app/Contents/Resources”

To explain why: Because the shell only sees regular ASCII quotes as quote characters, this gets interpreted as five arguments, instead of the intended four:

  cp -f myfile '“My' 'Program.app/Contents/Resources”'
# ^^ ^^ ^^^^^^  ^^^   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# |  |    |      |                  |
# 1  2    3      4                  5

...and since cp only accepts more than two non-option positional arguments when the last one is a directory, but Program.app/Contents/Resources” is not a directory that actually exists, it throws a usage error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM