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)
您#!/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
,您应该没问题。