In: Computer Science
UNIX/TERMINAL ASSIGNMENT - DIFFICULT
Could you please type line by line what I should be entering in the terminal command line to complete the assignment as instructed?
INSTRUCTIONS AS FOLLOWS:
In this lab you will create a script to backup certain number of oldest or newest files in the current directory into a compressed archived file. The objective of this lab is to familiarize and gain proficiency with the following:
• Use of command line arguments
• Use of conditional statement
• Use of for loops
You need to write a script named backup.sh which will receive 3 command line arguments. The arguments are:
• The 1st argument is the string “old” or “new” indicating whether
the oldest files or the newest files needs to be backed up
• The 2nd argument is an integer indicating how many files needs to be backed up.
• The 3rd argument is the name of archive file (tar file).
Your script should perform the following functions
• Check whether 3 arguments have been passed or not.
• If three arguments have not been passed display appropriate message and exit.
• Check whether the 1st argument is not the string “old” or “new” display appropriate message and exit.
• Create a temporary directory under current directory • Using a “for loop” copy all the required files in the temporary directory.
• Create an archive file of the copied files. The name of the archive files is the 3rd argument. Compress the archived file.
• Delete the temporary directory along with copied files.
Example execution: If user type the following ./backup.sh old 5 backup.tar The script will create a compressed archive file named backup.tar.gz in the current directory containing five oldest file in the current directory. ./backup.sh new 4 backup.tar The script will create a compressed archive file named backup.tar.gz in the current directory containing four newest t file in the current directory
How would I create a script named backup.sh and do the 3 arguments?
Have some Python and C++ experience, but Unix in Terminal is completely foreign to me so as much detail as possible would be appreciated.
Thanks!
Please find the below script, let me know if you face any issues
$ gedit backup.sh or vi $ backup.sh
then copy paste the below script save and execute it as ./backup.sh old 5 backup.tar from the terminal
like mentioned in the question
#!/bin/bash
if [ -z "$1" ]
then
echo 'Input new or old files! ex. ./backup.sh old 5 backup.tar'
exit 0
fi
if [ -z "$2" ]
then
echo 'please Input number of files to backup ! ex. ./backup.sh old 5 backup.tar'
exit 0
fi
if [ -z "$3" ]
then
echo 'please Input name of file to backup ! ex. ./backup.sh old 5 backup.tar'
exit 0
fi
mkdir ../tmp
if [ "new" == $1 ]
then
for f in $(ls -tr | tail -"$2") ; do cp -r $f ../tmp ; done
else
for f in $(ls -t | tail -"$2") ; do cp -r $f ../tmp ; done
fi
tar -cpzf $3 . ../tmp
rm -rf ../tmp
tar -C tmp -zxvf backup.tar commande used to untar the backup file