desgua's answer is proper and simple way, but what if you need a protable way ? POSIX defines cp
without --parent
flag, so it's not gonna work across all systems.
One option is to write it in Python if it's installed on the system:
#!/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])
This works as so:
$ ./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