Creating the backup2.sh using elif

We can revisit the script that we created to run the earlier backup. This script, $HOME/bin/backup.sh, prompts the user for the file type and the directory in which to store the backup. The tools used for the backup are find and cp.

With this new-found knowledge, we can now allow the script to run the backup using the command tar and the level of compression selected by the operator. There is no requirement to select the file type, as the complete home directory will be backed up, with the exclusion of the backup directory itself.

The operator can select the compression based on three letters: H, M, and L. The selection will affect the options passed to the tar command and the backup file created. The selection of high uses bzip2 compression, medium uses gzip compression, and low creates an uncompressed tar archive. The logic exists in the extended if statement that follows:

if [ $file_compression = "L" ] ; then 
tar_opt=$tar_l 
elif [ $file_compression = "M" ]; then 
tar_opt=$tar_m 
else 
tar_opt=$tar_h 
fi 

Based on the user selection, we can configure the correct options for the tar command. As we have three conditions to evaluate, the if, elif, and else statements are appropriate. To see how the variables are configured we can look at the following extract from the script:

tar_l="-cvf $backup_dir/b.tar --exclude $backup_dir $HOME" 
tar_m="-czvf $backup_dir/b.tar.gz --exclude $backup_dir $HOME" 
tar_h="-cjvf $backup_dir/b.tar.bzip2 --exclude $backup_dir $HOME" 

The complete script can be created as $HOME/bin/backup2.sh and should comprise the following code:

#!/bin/bash 
# Author: @theurbanpenguin 
# Web: www.theurbapenguin.com 
read -p "Choose H, M or L compression " file_compression 
read -p "Which directory do you want to backup to " dir_name 
# The next lines creates the directory if it does not exist 
test -d $HOME/$dir_name || mkdir -m 700 $HOME/$dir_name 
backup_dir=$HOME/$dir_name 
tar_l="-cvf $backup_dir/b.tar --exclude $backup_dir $HOME" 
tar_m="-czvf $backup_dir/b.tar.gz --exclude $backup_dir $HOME" 
tar_h="-cjvf $backup_dir/b.tar.bzip2 --exclude $backup_dir $HOME" 
if [ $file_compression = "L" ] ; then 
tar_opt=$tar_l 
elif [ $file_compression = "M" ]; then 
tar_opt=$tar_m 
else 
tar_opt=$tar_h 
fi 
tar $tar_opt 
exit 0 

When we execute the script, we need to select H, M, or L in upper case, as this is how the selection is made within the script. The following screenshot shows the initial script execution, where the selection for M has been made:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.5.86