Linux:如果目标目录不存在,则复制并创建它

新手上路,请多包涵

我想要一个命令(或者可能是 cp 的一个选项)来创建目标目录(如果它不存在)。

例子:

 cp -? file /path/to/copy/file/to/is/very/deep/there

原文由 flybywire 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 817
2 个回答
mkdir -p "$d" && cp file "$d"

cp 没有这样的选项)。

原文由 Michael Krelin - hacker 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果以下两个都为真:

  1. 您正在使用 cp 的 GNU 版本(而不是例如 Mac 版本),并且
  2. 您正在从一些现有的目录结构中复制,您只需要重新创建它

然后你可以用 --parents 标志 cp 来做到这一点。从信息页面(可在 http://www.gnu.org/software/coreutils/manual/html_node/cp-invocation.html#cp-invocation 或使用 info cpman cp ):

>  --parents
>      Form the name of each destination file by appending to the target
>      directory a slash and the specified name of the source file.  The
>      last argument given to `cp' must be the name of an existing
>      directory.  For example, the command:
>
>           cp --parents a/b/c existing_dir
>
>      copies the file `a/b/c' to `existing_dir/a/b/c', creating any
>      missing intermediate directories.
>
> ```

例子:

/tmp \( mkdir foo /tmp \) mkdir foo/foo /tmp \( touch foo/foo/foo.txt /tmp \) mkdir bar /tmp \( cp --parents foo/foo/foo.txt bar /tmp \) ls bar/foo/foo foo.txt

”`

原文由 Paul Whipp 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题