How to handle space in filename in bash script?

bash

Solution

There are two possibilities:

TARGET="/media/USB DISK/Backup/"
rsync -av --delete ~/Data "${TARGET}"

or

TARGET=/media/USB\ DISK/Backup/
rsync -av --delete ~/Data "${TARGET}"

The first one preserves the space by quoting the whole string. The second one preserves the space by escaping it with a backslash. Also, the argument to the `rsync` command needs to be quoted.

When the string is both double-quoted and the space is preceded by a backslash, as in `TARGET="a\ b"`, the result is that `TARGET` contains a literal backslash which is probably not what you wanted. For more details, see the section entitled "Quoting" in `man bash`.

Problem

I want to automate rsyncing, and tried the following code: ``` TARGET="/media/USB\ DISK/Backup/" rsync -av --delete ~/Data ${TARGET} ``` but the execution results in the following error: ``` rsync: link_stat "/media/USB\" failed: No such file or directory (2) rsync: mkdir "/home/DISK/BACKUP" failed: No such file or directory (2) ``` because of the 'space' in the target filename. However, when I `echo` the command I can use that to run on the shell directly. How to do it correctly (which brackets, with backslash or without?) and why?

Original source