Problem with variables and bash script

From the command line:

dions-air:scripts dion$ ls -l /Users/dion/Library/Application\ Support/Garmin/Devices/3816821036/History/2014-06-07-055251.TCX
-rw-r--r--  1 dion  staff  157934  7 Jun 06:55 /Users/dion/Library/Application Support/Garmin/Devices/3816821036/History/2014-06-07-055251.TCX

works as expected
However in a script:

#!/bin/bash

GARMIN_DEVICE_NUMBER="3816821036"
sourcefile="/Users/dion/Library/Application\ Support/Garmin/Devices/${GARMIN_DEVICE_NUMBER}/History/2014-06-07-055251.TCX"
destfiles="/tmp/"
ls -l "${sourcefile}"
echo cp -- "${sourcefile}" "${destfiles}"
cp -- "${sourcefile}" "${destfiles}"

the following is returned

dions-air:scripts dion$ ./test.command 
ls: /Users/dion/Library/Application\ Support/Garmin/Devices/3816821036/History/2014-06-07-055251.TCX: No such file or directory
cp -- /Users/dion/Library/Application\ Support/Garmin/Devices/3816821036/History/2014-06-07-055251.TCX /tmp/
cp: /Users/dion/Library/Application\ Support/Garmin/Devices/3816821036/History/2014-06-07-055251.TCX: No such file or directory

Some help would be appreciated. I have no idea where I have gone wrong. Thanks.

Note that in the successful ls , the output does not contain a backslash character before the space. In that ls command, you used a backslash to escape the space to keep the shell from treating it as two filename operands.

In the cases that failed you quoted the filenames AND escaped the space. You need to do one or the other; not both. If at all possible, NEVER create filenames that contain a space, tab, or newline character. To solve the problem in this case, remove the \ character from the quoted strings when you assign the value to sourcefile . That is, change:

sourcefile="/Users/dion/Library/Application\ Support/Garmin/Devices/${GARMIN_DEVICE_NUMBER}/History/2014-06-07-055251.TCX"

to:

sourcefile="/Users/dion/Library/Application Support/Garmin/Devices/${GARMIN_DEVICE_NUMBER}/History/2014-06-07-055251.TCX"
1 Like

That worked.:slight_smile:

I was not aware that the issue was you should not escape and quote.

In terms of the spaces, I agree; however, on apple, they create a folder called "Application Support" and there is no way to get around that, all software expects things to be in that folder. It is one of the annoyances of apple.

Thanks for your help. I really appreciate it.