I have created the following script that move old days files as defined from source directory to destination directory. It is working perfectly.
#!/bin/bash
echo "Enter Your Source Directory"
read soure
echo "Enter Your Destination Directory"
read destination
echo "Enter Days"
read days
find "$soure" -type f -mtime "-$days" -exec mv {} "$destination" \;
echo "Files which were $days Days old moved from $soure to $destination"
This script moves files great, It also move files of source subdirectory, but it doesn't create subdirectory into destination directory. I want to implement this additional feature in it.
with example
/home/ketan : source directory
/home/ketan/hex : source subdirectory
/home/maxi : destination directory
When I run this script , it also move hex's files in maxi directory, but I need that same hex should be created into maxi directory and move its files in same hex there.
Best Answer
Instead of running
mv /home/ketan/hex/foo /home/maxi
, you'll need to vary the target directory based on the path produced byfind
. This is easier if you change to the source directory first and runfind .
. Now you can merely prepend the destination directory to each item produced byfind
. You'll need to run a shell in thefind … -exec
command to perform the concatenation, and to create the target directory if necessary.Note that to avoid quoting issues if
$destination
contains special characters, you can't just substitute it inside the shell script. You can export it to the environment so that it reaches the inner shell, or you can pass it as an argument (that's what I did). You might save a bit of execution time by groupingsh
calls:Alternatively, in zsh, you can use the
zmv
function, and the.
andm
glob qualifiers to only match regular files in the right date range. You'll need to pass an alternatemv
function that first creates the target directory if necessary.