In: Computer Science
Write a shell script (to run on the Bourne shell) called cp2.sh to copy all the files from two named directories into a new third directory. Timestamps must be preserved while copying files from one directory into another.
Task Requirements
Three directory names must be supplied as arguments to your script when it is executed by the user.
In the beginning of your script you need to check that the first two directory names provided (e.g. dir1 and dir2) exist under the current directory. If they do not exist, your script must display an error message and then it should exit.
The third directory argument to the script will specify a new directory name (for example, dir3). This directory must not currently exist (i.e. the creation of e.g. dir3 should be one of the actions of your script). If the directory already exists, your script should display an error message and exit.
The script will first copy all of the files from dir1 into dir3. Your script output must indicate which files have been copied.
The script will then copy every file from dir2 to dir3 subject to the following conditions:
only copy if the file from dir2 is not already present in dir3; or
only copy if the file from dir2 is newer than the same file in dir3. The newer file
will overwrite the existing version in dir3.
Your script output must indicate which files have been copied.
Clean up - remove all temporary files created (if any) at the end of your script.
Your script must generate output similar to the example output shown below.
Below is the shell script code. You can save it to a file with name cp2.sh. I have written the script code to cover all the requirements you have mentioned. I have added the comments as well to demonstrate that what the particular code will be doing.
# Setup input arguements into the variables
DIR1=$0
DIR2=$1
DIR3=$2
DIR4=$PWD
# Check if directory are sub-directories of current directory
if [[ ! "$DIR4" == "$DIR1"* ]]; then
echo "DIR1 does not exist under the current directory. Exiting the script"
exit 0
elif [[ ! "$DIR4" == "$DIR2"* ]]; then
echo "DIR2 does not exist under the current directory. Exiting the script"
fi
# Check if directory already exists else create the directory
if [ -d $DIR3 ]
then
echo "Directory already exists. Exiting the script"
exit 0
else
mkdir $DIR3
fi
#Copy all files from DIR1 to DIR3
cp -p -v $DIR1/* $DIR3
#Copy all files from DIR2 to DIR3
cp -p -u -v $DIR2/* $DIR3
exit 0
Hope it helps.