Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to make mv create the directory to be moved to if it doesn't exist?

So, if I'm in my home directory and I want to move foo.c to ~/bar/baz/foo.c , but those directories don't exist, is there some way to have those directories automatically created, so that you would only have to type

mv foo.c ~/bar/baz/  

and everything would work out? It seems like you could alias mv to a simple bash script that would check if those directories existed and if not would call mkdir and then mv, but I thought I'd check to see if anyone had a better idea.

like image 352
Paul Wicks Avatar asked Feb 13 '09 21:02

Paul Wicks


People also ask

How do you create a directory if it does not exist?

When you want to create a directory in a path that does not exist then an error message also display to inform the user. If you want to create the directory in any non-exist path or omit the default error message then you have to use '-p' option with 'mkdir' command.

Can mv move a directory?

The mv command moves files and directories from one directory to another or renames a file or directory. If you move a file or directory to a new directory, it retains the base file name. When you move a file, all links to other files remain intact, except when you move it to a different file system.

How do you mkdir only if a DIR does not already exist?

You can either use an if statement to check if the directory exists or not. If it does not exits, then create the directory. You can directory use mkdir with -p option to create a directory. It will check if the directory is not available it will.

Does mv move all files in directory?

The mv command is used to move files and directories from one place to another. We can also use it to rename files and directories. This will move all the files from /path/subfolder to /path/ except for hidden files and directories.


2 Answers

How about this one-liner (in bash):

mkdir --parents ./some/path/; mv yourfile.txt $_ 

Breaking that down:

mkdir --parents ./some/path # if it doesn't work; try mkdir -p ./some/path 

creates the directory (including all intermediate directories), after which:

mv yourfile.txt $_ 

moves the file to that directory ($_ expands to the last argument passed to the previous shell command, ie: the newly created directory).

I am not sure how far this will work in other shells, but it might give you some ideas about what to look for.

Here is an example using this technique:

$ > ls $ > touch yourfile.txt $ > ls yourfile.txt $ > mkdir --parents ./some/path/; mv yourfile.txt $_ $ > ls -F some/ $ > ls some/path/ yourfile.txt 
like image 183
KarstenF Avatar answered Oct 24 '22 05:10

KarstenF


mkdir -p `dirname /destination/moved_file_name.txt`   mv /full/path/the/file.txt  /destination/moved_file_name.txt 
like image 28
Billmc Avatar answered Oct 24 '22 05:10

Billmc