Table of contents
- 1. Write a BASH script to create a backup of the current directory that you are working on.
- 2. Write a BASH script that will add two nos, which are supplied as command line arguments, and if this two nos are not given, show error and its correct usage.
- 3. Write a BASH script to find out the biggest number from the given three numbers. The numbers should be provided as command line arguments and throw error if not provided.
This post assumes that you have read the bash script beginner guideso that you know how to give file permissions and how to execute the bash script.
1. Write a BASH script to create a backup of the current directory that you are working on.
Usage: ./backup.sh
No command line arguments are needed as the script will take a backup of the current directory that you are working on.
#!/bin/bash
echo "Creating a backup of the $(pwd) directory"
tar -cvf ~/bash-scripting/mybackup_"$(date +%d-%m-%Y_%H-%M-%S)".tar $(pwd) 2>/dev/null
echo "Finished backing up $(pwd)"
Output of the above script is as follows:
After executing the script, we can see that a new .tar file was created with current date and time. This is done so that the .tar won't get overwritten each time a backup is created.
2. Write a BASH script that will add two nos, which are supplied as command line arguments, and if this two nos are not given, show error and its correct usage.
#!/bin/bash
# Author: Sebin Sebastian
# Created: 24th March 2022
# Last Modified: 24nd March 2022
# Description:
# Write shell script that will add two nos, which are supplied as command line argument,
# and if this two nos are not given show error and its usage
# Usage
# ./filename num1 num2
if [ -z "$2" ] ; then
echo "No input arguments."
echo "usage: $0 <arg1> <arg2>"
exit 1
else
echo "The sum of $1 and $2 is: "
echo $(( ${1:-0} + ${2:-0}))
exit 0
fi
exit 0
The output of the above script is as follows.
3. Write a BASH script to find out the biggest number from the given three numbers. The numbers should be provided as command line arguments and throw error if not provided.
#!/bin/bash
# Author: Sebin Sebastian
# Created: 24th March 2022
# Last Modified: 24nd March 2022
# Description:
# Write Script to find out biggest number from given three nos.
# Nos are supplied as command line arguments.
# Print error if sufficient arguments are not supplied.
# Usage
# The solution has been explained in the readme file. Refer the readme
# file along with this solution.
if [ $# -ne 3 ]; then
echo "No arguments supplied"
echo "usage: $0 <arg1> <arg2> <arg3>"
exit 1
fi
if [ $1 -eq $2 ] && [ $1 -eq $3 ]; then
echo "All numbers are equal."
elif [ $1 -gt $2 -a $1 -gt $3 ]; then
echo "$1 is the largest."
elif [ $2 -gt $1 -a $2 -gt $3 ]; then
echo "$2 is the largest."
else
echo "$3 is the largest."
fi