首页 > 解决方案 > cp 不适用于文件路径有空格的源变量

问题描述

我想将所有内容从源目录(目录名包含空格)复制到目标。

我的工作目录中的命令输出ls -l如下:

drwxrwxr-x 2 ubuntu ubuntu 4096 Apr  5 06:39  destination
drwxrwxr-x 2 ubuntu ubuntu 4096 Apr  5 06:08 'source directory with spaces'

当我这样做时 -cp -r ./source\ directory\ with\ spaces/. destination/该命令运行良好,并且“带空格的源目录”文件夹中的文件(A.txt、B.txt 和 C.txt)被成功复制。

我想让它动态化,所以我将源位置存储在一个变量中:

fileVar="./source\ directory\ with\ spaces/."

现在,当我使用以下任一命令点击 cp 命令时:

cp -r $fileVar destination/

错误:

cp: cannot stat './source\': No such file or directory
cp: cannot stat 'directory\': No such file or directory
cp: cannot stat 'with\': No such file or directory
cp: cannot stat 'spaces/A.txt': No such file or directory

或者

cp -r "$fileVar" destination/

错误:

cp: cannot stat './source\ directory\ with\ spaces/A.txt': No such file or directory

我该如何解决?提前致谢。

标签: shellescapingfilenamesquotesspaces

解决方案


推荐阅读