Câu trả lời của desgua là cách thích hợp và đơn giản, nhưng nếu bạn cần một cách có thể tin được thì sao? POSIX định nghĩa cpkhông có --parentcờ, vì vậy nó sẽ không hoạt động trên tất cả các hệ thống.
Một tùy chọn là viết nó bằng Python nếu nó được cài đặt trên hệ thống:
#!/usr/bin/env python3
from os import makedirs
from os.path import exists,basename
from shutil import copyfile
from sys import argv
if len(argv) < 3:
print('Not enough args',file=stderr)
exit(1)
filename = basename(argv[2])
dirs = argv[2].replace(filename,'')
makedirs(dirs)
copyfile(argv[1],argv[2])
Điều này hoạt động như vậy:
$ ./mkdircp.py /etc/passwd $HOME/foodir/bardir/passwd.copy
$ stat --printf "%F\n" $HOME/foodir/bardir/passwd.copy
regular file
$ head -n 1 $HOME/foodir/bardir/passwd.copy
root:x:0:0:root:/root:/bin/bash
the_filebạn cần thêm một/vào cuối đường dẫn thư mục mới của bạn.