如何在bash脚本中处理文件名中的空间? [英] How to handle space in filename in bash script?

查看:60
本文介绍了如何在bash脚本中处理文件名中的空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想自动执行rsyncing,并尝试了以下代码:

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)

因为目标文件名中的空格".但是,当我 echo 命令时,我可以使用该命令直接在shell上运行.

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?

推荐答案

有两种可能性:

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.

这篇关于如何在bash脚本中处理文件名中的空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆