Linux: copy and create destination dir if it does

2019-01-04 06:03发布

I want a command (or probably an option to cp) that creates the destination directory if it does not exist.

Example:

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

16条回答
forever°为你锁心
2楼-- · 2019-01-04 06:40

cp has multiple usages:

$ cp --help
Usage: cp [OPTION]... [-T] SOURCE DEST
  or:  cp [OPTION]... SOURCE... DIRECTORY
  or:  cp [OPTION]... -t DIRECTORY SOURCE...
Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.

@AndyRoss's answer works for the

cp SOURCE DEST

style of cp, but does the wrong thing if you use the

cp SOURCE... DIRECTORY/

style of cp.

I think that "DEST" is ambiguous without a trailing slash in this usage (i.e. where the target directory doesn't yet exist), which is perhaps why cp has never added an option for this.

So here's my version of this function which enforces a trailing slash on the dest dir:

cp-p() {
  last=${@: -1}

  if [[ $# -ge 2 && "$last" == */ ]] ; then
    # cp SOURCE... DEST/
    mkdir -p "$last" && cp "$@"
  else
    echo "cp-p: (copy, creating parent dirs)"
    echo "cp-p: Usage: cp-p SOURCE... DEST/"
  fi
}
查看更多
淡お忘
3楼-- · 2019-01-04 06:40

Just to resume and give a complete working solution, in one line. Be careful if you want to rename your file, you should include a way to provide a clean dir path to mkdir. $fdst can be file or dir. Next code should work in any case.

fsrc=/tmp/myfile.unk
fdst=/tmp/dir1/dir2/dir3/myfile.txt
mkdir -p $(dirname ${fdst}) && cp -p ${fsrc} ${fdst}

or bash specific

fsrc=/tmp/myfile.unk
fdst=/tmp/dir1/dir2/dir3/myfile.txt
mkdir -p ${fdst%/*} && cp -p ${fsrc} ${fdst}
查看更多
做个烂人
4楼-- · 2019-01-04 06:46
rsync file /path/to/copy/file/to/is/very/deep/there

This might work, if you have the right kind of rsync.

查看更多
Evening l夕情丶
5楼-- · 2019-01-04 06:46

Copy from source to an non existing path

mkdir –p /destination && cp –r /source/ $_

NOTE: this command copies all the files

cp –r for copying all folders and its content

$_ work as destination which is created in last command

查看更多
家丑人穷心不美
6楼-- · 2019-01-04 06:48

Shell function that does what you want, calling it a "bury" copy because it digs a hole for the file to live in:

bury_copy() { mkdir -p `dirname $2` && cp "$1" "$2"; }
查看更多
做自己的国王
7楼-- · 2019-01-04 06:49
mkdir -p "$d" && cp file "$d"

(there's no such option for cp).

查看更多
登录 后发表回答