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

例子:

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

当前回答

mkdir -p "$d" && cp file "$d"

(cp没有这样的选项)。

其他回答

只需在你的.bashrc中添加以下代码,如果需要可以调整。适用于Ubuntu。

mkcp() {
    test -d "$2" || mkdir -p "$2"
    cp -r "$1" "$2"
}

如 如果您想将“test”文件复制到目标目录“d” 使用,

mkcp test a/b/c/d

MKCP将首先检查目标目录是否存在,如果不存在则创建并复制源文件/目录。

install -D file -m 644 -t /path/to/copy/file/to/is/very/deep/there

我尊重上面的答案,我更喜欢使用rsync如下所示:

$  rsync -a directory_name /path_where_to_inject_your_directory/

例子:

$ rsync -a test /usr/local/lib/

虽然已经很晚了,但对新手还是有帮助的。如果你需要自动创建文件夹,rsync应该是你最好的朋友。

rsync /path/to/sourcefile /path/to/tragetdir/thatdoestexist/

仅适用于macOS

rsync -R <source file path> destination_folder

对于macOS -父母cp选项不工作