Alex Rivera | Logout

Unix - create path of folders and file

Asked 2012-02-26T12:11:23.897
156

I know you can do mkdir to create a directory and touch to create a file, but is there no way to do both operations in one go?

i.e. if I want to do the below when the folder other does not exist:

cp /my/long/path/here/thing.txt /my/other/path/here/cpedthing.txt

Error:

cp: cannot create regular file `/my/other/path/here/cpedthing.txt': No such file or directory

Has anyone come up with a function as a workaround for this?

Edit
Report

2 Answers

14
#!/bin/sh
for f in "$@"; do mkdir -p "$(dirname "$f")"; done
touch "$@"
answered 2012-02-26T12:14:38.210
2
if [ ! -d /my/other ]
then
   mkdir /my/other/path/here
   cp /my/long/path/here/thing.txt /my/other/path/here/cpedthing.txt
fi
answered 2012-02-29T09:06:04.277

Your Answer