Bash Scripting Codes


Prerequisite :
You have to know the following things :
After going through the above contents, here is the problems on that :
Codes:
Problem 1 :
Write a script that will take a file path and a folder path in interactive mode (Means, it will prompt messages asking to provide the inputs one by one) and take a backup of the file by copying it into the folder path. If the folder does not exist, the script should create the folder and take the backup then.
Solution :
#!/bin/bash
read -p "Enter path of file : " _file
read -p "Enter path of folder : " _folder
if [ -d "$_folder" ]
then 
cp -i "$_file"  "$_folder"
else
mkdir  "$_folder"
cp -i "$_file"  "$_folder"
fi

Problem 2 :
Write a script that will take three numbers which represent three sides of a triangle as command line argument inputs. Your script should check the validity of the inputs given by the user. The script should exit with following exit status - 
    1. Exit status = 1, when number of parameters are not three.

    2. Exit status = 2, when three sides does not form a valid triangle

Otherwise, the script should terminate normally. It should not show any kind of output message in any of these scenarios.
Solution:
#!/bin/bash
a=$1
b=$2
c=$3
if [ -z "$a" ] || [ -z "$b" ] || [ -z "$c" ]
then
exit 1
elif [ $(($a + $b)) -lt $c ] || [ $(($a + $c)) -lt $b ] || [ $(($c + $b)) -lt $a ]
then
exit 2
fi

Problem 3 :
Write a script that should take three sides of a triangle as command line arguments. It will then invoke the script you write for question 2 to check the validity of the inputs. If the second script terminates with exit status 1, you should show a message “A triangle has only three sides!”. If the second script terminates with exit status 2, you should show a message “These three sides cannot form a triangle!”. Otherwise your program should check whether the three sides form a right-angled triangle or not. Then, prompt the user whether the sides form a right-angled triangle or not with an appropriate message.
Solution:
#!/bin/bash
a=$1
b=$2
c=$3
if [ -z "$a" ] || [ -z "$b" ] || [ -z "$c" ]
then
echo "A triangle has only three sides!"
exit 1
elif [ $(($a + $b)) -lt $c ] || [ $(($a + $c)) -lt $b ] || [ $(($b + $c)) -lt $a ]
then
echo "These three sides can not form a triangle!"
exit 2
fi
if [ $(($a**2 + $b**2)) -eq $(($c**2)) ] || [ $(($a**2 + $c**2)) -eq $(($b**2)) ] || [ $(($b**2 + $c**2)) -eq $(($a**2)) ]
then
echo "These three sides form a right-angled triangle!"
else
echo "These three sides do not form a right-angled triangle!"
fi