Scripting style: • Specify the shell for executing the script in the first line
ID: 3697727 • Letter: S
Question
Scripting style:
• Specify the shell for executing the script in the first line
#!/bin/bash
• Write comments in the script
#!/bin/bash
# This is a script for hw6
# author: abc xyz, date: xx/xx
Question1 (15 points):
Use vim to write a script “mycp” that satisfies the following requirements:
1. The general usage of the script is “./mycp src_dir dst_dir”, where
src_dir and dst_dir are two arguments. The function of the script is to copy
all the files and directories under src_dir to dst_dir.
2. Your script needs to first check the number of arguments. If the arguments are
fewer than 2, print out a usage message and exit. (hint: use “man test” to
check how to test “less than”)
3. Your script should then check whether src_dir exists. If not, print out an error
message “The source directory cannot be found.” and exit. (hint: use “man test”
to check how to test “not”)
4. In addition, your script needs to check whether dst_dir exists. If not, the
script should create the dst_dir directory.
5. Finally, your script needs to copy all the files and directories under src_dir to
dst_dir. (“cp –r dir1/* dir2” will copy everything under dir1 to
dir2.)
Explanation / Answer
#!/bin/bash
# This is a script for hw6
# test if we have two arguments, exit with warning if we don't
if (($# != 2)); then
echo "Usage $0 src_dir dest_dir"
exit 1
#endif
else
# Check Source Directory Exist
if [ -d "$1" ]
then
echo "Source Directory $1 exists."
else
echo "Error: Source Directory $1 does not exists."
fi
# Check destination Directory Exist
if [ -d "$2" ]
then
echo "Destination Directory $2 exists."
cp -r "$1/." "$2/"
else
echo "Error: Destination Directory "$2" does not exists."
fi
fi
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.