Into the Linux-verse
Table of contents
Hey guys, this is the last blog of this series hope you enjoyed the Linux workshop series. Let's see what I added to my mind palace...
Functions
A function is a collection of statements that execute a specified task. Its main goal is to break down a complicated procedure into simpler subroutines that can subsequently be used to accomplish the more complex routine. For the following reasons, functions are popular:
Assist with code reuse.
Enhance the program’s readability.
Modularize the software.
Allow for easy maintenance.
The basic syntax of function in shell scripting -
#Syntax
function_name () {
#commands to be executed.
#body of the function.
}
function_name #Function call.
#Example
#!/bin/bash
create_user () {
echo "Enter the username : "
read username
useradd ${username}
echo "You have created the user : ${username}"
}
create_user
#Output
Enter the username :
TestUser
You have created the user : TestUser
Case Statement
A case statement in bash scripts is used when a decision has to be made against multiple choices. In other words, it is useful when an expression can have multiple values. This methodology can be seen as a replacement for multiple if-statements in a script. Case statement has an edge over if statements because it improves the readability of our code and they are easier to be maintained. Case statements in a Bash script are quite similar to Case statements in any other programming language. But unlike any programming language, the Bash Case statement stops continuing the search as soon as the match occurs. In simple words, they don’t require any break statement that is mandatory to be used in C to stop searching for a pattern further.
The basic syntax of the case statement -
#Syntax
case {expression} in
Pattern_Case_1)
#Statements to be executed
;;
Pattern_Case_1)
#Statements to be executed
;;
Pattern_Case_N)
#Statements to be executed
;;
*) #This is used for the cases which are exceptional
#Statements to be executed
;;
esac
Example -
#!/bin/bash
echo "Choose the colour : "
echo "1) Red"
echo "2) Green"
echo "3) Blue"
read colour
case {colour} in
Red)
echo "You have choosen the Red colour..!!"
;;
Green)
echo "You have choosen the Green colour..!!"
;;
Blue)
echo "You have choosen the Blue colour..!!"
;;
*)
echo "The colour you choose is unavailable.."
;;
esac
Output :
Enter the username :
TestUser
You have created the user : TestUser
Hope you loved the blog series from a naive blogger... See you in another one still then stay tuned...
Subscribe to my newsletter
Read articles from Arfat Kadvekar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Arfat Kadvekar
Arfat Kadvekar
A Naive Developer