如何在 bash 脚本中复制多个文件

Mic*_*a93 0 scp cp shell-script

我想知道如何在 bash 脚本中复制或 shell 复制多个文件。我的意思是

cp /path/to/source/{file1,file2,file3} /path/to/dest
Run Code Online (Sandbox Code Playgroud)

scp /path/to/source/{file1,file2,file3} user@host:/path/to/dest
Run Code Online (Sandbox Code Playgroud)

会工作正常,但作为例子

#!/bin/sh
scp /path/to/source/{file1,file2,file3} user@host:/path/to/dest
Run Code Online (Sandbox Code Playgroud)

会抛出这样的错误:

/path/to/source/{file1,file2,file3}: No such file or directory
Run Code Online (Sandbox Code Playgroud)

如果您将复制或 shell 复制单个文件,则它可以工作,因此问题是多个文件。如果我将*用于所有文件但我不想复制所有文件,它也有效。我应该只复制选定的文件,因为在两个文件夹中都是名称相同但内容不同的文件。从而复制所有文件然后删除不需要的文件是行不通的。

为了更好地理解以下内容将起作用:

#!/bin/sh
scp /path/to/source/file1 user@host:/path/to/dest
Run Code Online (Sandbox Code Playgroud)

还有以下内容:

#!/bin/sh
scp /path/to/source/* user@host:/path/to/dest
Run Code Online (Sandbox Code Playgroud)

所以它与正确使用{ ... }多个文件有关,这些文件将在终端内工作,但如果我在其中运行 bash 脚本则不会。

提前致谢。

//编辑:

如果我用 cp 尝试,我会添加错误:

cp: cannot stat '/path/to/source/{file1,file2,file3}': No such file or directory
Run Code Online (Sandbox Code Playgroud)

ter*_*don 6

#!/bin/sh的脚本中有,这意味着它将由 运行sh,而不是bash. 在许多 Debian 派生系统上,例如 Ubuntu,/bin/sh是基本 POSIX shell 的符号链接dash。不支持您使用的大括号扩展dash

$ dash
$ echo {foo,bar}
{foo,bar}
Run Code Online (Sandbox Code Playgroud)

这意味着该命令cp /path/to/source/{file1,file2,file3} /path/to/dest正在寻找一个名为{file1,file2,file3}. 简单的解决方法是bash改用。只需将您的 shebang 线从 更改#!/bin/sh#!/bin/bash,您应该没问题。

  • @Micha93 哦不,请不要这样做,这是一个完全不必要的安全漏洞,不必要的复杂代码并且非常脆弱(如果您的一个文件中包含像空格这样简单的内容,它就会损坏)。这也毫无意义,您可以使用数组并避免整个问题。请发布一个新问题。 (4认同)