Shell Script to copy files in a folder

A shell script to find all the files in the given path recursively and then copying them in the target folder

#!/bin/sh
#################################################################
# A shell script to go through a directory recursively and copy #
#################################################################

# this is full path to the folder from where the files need to be copied.
path="/home/Music/" 

# this is the target folder in which we need to copy the files.
folder="store/"

# creating the target folder in it doesnt exist
mkdir -p $folder

# running find command to list all the files in the given path
for i in `find $path`
do
	# using sudo to neglect the warnings n permissions for the file's access
	# copying the files in the target folder by sudo permissions
	sudo cp $i $folder
	echo "File:$i is copied"
	done
done

Save the file with the name copy.sh, Note: here .sh extension isn’t necessary, we use for readability. It doesnt make any difference to the OS.

Change the permissions of the file using the chmod command to make it executable.

$ chmod 700 copy.sh

Run the script in the shell and see it working. It will copy all the files in the store folder.

$ ./copy.sh

You can modify the script to find and copy the files of required kind of properties, using the find utilities options. All you need to do is to supply the option to the find command next to the for loop in the script.

Eg. For only .mp3 files we can modify the find as:

for i in `find $path`

to

for i in `find $path -name *.mp3`

We can also modify the action copying to delete or else by changing the code as

sudo cp $i $folder

to

sudo cat $i # for listing the data of the files on console.

In the same way it can be used to search for any particular kind of files on the system by changinig the find options accordingly.(Such as , by size, by creation time, by extensions etc.)

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: