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

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


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; trymkdir -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$ > lsyourfile.txt$ > mkdir --parents ./some/path/; mv yourfile.txt $_$ > ls -Fsome/$ > ls some/path/yourfile.txt


mkdir -p `dirname /destination/moved_file_name.txt`  mv /full/path/the/file.txt  /destination/moved_file_name.txt


Save as a script named mv.sh

#!/bin/bash# mv.shdir="$2" # Include a / at the end to indicate directory (not filename)tmp="$2"; tmp="${tmp: -1}"[ "$tmp" != "/" ] && dir="$(dirname "$2")"[ -a "$dir" ] ||mkdir -p "$dir" &&mv "$@"

Or put at the end of your ~/.bashrc file as a function that replaces the default mv on every new terminal. Using a function allows bash keep it memory, instead of having to read a script file every time.

function mvp (){    dir="$2" # Include a / at the end to indicate directory (not filename)    tmp="$2"; tmp="${tmp: -1}"    [ "$tmp" != "/" ] && dir="$(dirname "$2")"    [ -a "$dir" ] ||    mkdir -p "$dir" &&    mv "$@"}

Example usage:

mv.sh file ~/Download/some/new/path/ # <-End with slash

These based on the submission of Chris Lutz.