且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在bash脚本中处理文件名中的空间?

更新时间:2022-03-29 19:49:46

有两种可能性:

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

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

第一个通过引用整个字符串来保留空间.第二个通过用反斜杠转义来保留空间.另外, rsync 命令的参数需要加引号.

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.

当字符串都用双引号引起来并且空格前​​面带有反斜杠时,如 TARGET ="a \ b" 所示,结果是 TARGET 包含文字反斜杠,可能不是您想要的.有关更多详细信息,请参见 man bash 中标题为报价"的部分.

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.