Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle space in filename in bash script?

Tags:

bash

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?

like image 727
Alex Avatar asked Dec 09 '13 20:12

Alex


1 Answers

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.

like image 74
John1024 Avatar answered Oct 27 '22 00:10

John1024