Skip to content

Instantly share code, notes, and snippets.

@nasikshafeek
Last active July 2, 2016 11:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nasikshafeek/7ada942e034781cd523c95ebb11c28af to your computer and use it in GitHub Desktop.
Save nasikshafeek/7ada942e034781cd523c95ebb11c28af to your computer and use it in GitHub Desktop.
Bash script to move file or directories by creating a directory if the target directory does not exist.
#!/bin/bash
# mvdir file path/to/folder
# Condition to test whether there are 2 input
# And condtition to test whether first parameter is a file/directory
if [ $# -eq 2 ] && [ -e $1 ]
then
file=$1;
targetPath=$2;
mkdir -p "$targetPath" &&
mv "$file" "$targetPath";
else
echo "USAGE: \$ mvdir [file] [path_to_folder]"
fi
@nasikshafeek
Copy link
Author

nasikshafeek commented Jul 2, 2016

Installing this would be very simple.
Copy the above code from the very first line to the last do a file named mvdir.sh (No problem in removing line 2,3,4 & 5. But not the other lines). Or instead do a clone of the above file. For example will say that you have this file in your /home/{user}/mybash/mvdir.sh.

Now will make the mvdir command be accessed from anywhere in the system. First make the mvdir.sh file executable.
$ chmod +x /home/{user}/mybash/mvdir.sh
Make it available anywhere from the command prompt.
$ sudo ln -s /home/{user}/mybash/mvdir.sh /usr/local/bin/mvdir

Usage of this command is similar to the move (mv) command. First parameter is the file/directory that is supposed to be moved. Second parameter is the directory that this file is moved into, if the target directory does not exist, it would create one and move the file into that particular directory.

$ mvdir file_to_be_moved directory_to_be_moved_into

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment