1

I know there is a thread on this site for creating a directory when using cp but my question is a little different. I want to copy a file in a new destination in linux, but some part of the path might not exist and I wanted to know whether it is possible to create that path without separating directory name from file name, for example, imagine I have a variable that contains the prefix for new files $prefixdir and I want every file to be copied in that location.

prefixdir=/home/akj/newpath
list="$(ls /somelocation...)"
for l in $list
do
   cp -v $l "$prefixdir$l"
done

From the example it is obvious that there can be some directories that don't exist under new location and because of file names I can't use mkdir "$prefixdir$l". I know I can separate file name from directory name and then use mkdir but I was wondering if there were an elegant way to do that.

EDIT:

To just clarify my question imagine I want to copy /lib/tt/test.so and my $prefixdir is /home/akj/. Also imagine that lib/tt doesn't exist, so my cp command would fail. I also can't use mkdir -p because of test.so in the path.

Thanks.

AKJ88
  • 713
  • 2
  • 10
  • 20

1 Answers1

1

If you have Gnu coreutils (normally you will on linux), you can use:

install -m 0644 -D source_file dest_filename

which automatically creates necessary directories.

The -m 0644 flag sets the permissions of the new file to 0644 (rw-r--r--); you need that because the default is to set the permissions to rxwr-xr-x (on the assumption that the file should be executable, since that's the usual use case) rather than copying the permissions of the original file.

rici
  • 234,347
  • 28
  • 237
  • 341