Jump into the Linux world
Table of contents
Hi guys! I hope you all read my previous blog.
So, today we covered the above topics.
#learnwithpra9
Functions
In Linux shell scripting, a function is a self-contained block of code that performs a specific task or set of tasks.
Its main goal is to break down a complicated procedure into simpler subroutines that can subsequently be used to accomplish the more complex routine.
Syntax:
function-name() { statement }
Example:
#!/bin/bash create_user () { echo "Enter user name:" read username useradd ${username} echo "User is created: ${uesrname}" } crete_uesr
Output:
Enter uesr name: SoulTroy User is created: SoulTroy
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.
It allows you to perform different actions depending on the value of a single variable, reducing the need for multiple if-else statements.
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.
Syntax:
case {expression} in Pattern_Case_1) #Statements to be executed ;; Pattern_Case_2) #Statements to be executed ;; Pattern_Case_N) #Statements to be executed ;; *) #Statements to be executed ;; esac
Example:
#!/bim/bash echo "Choose the color: " echo "1) Red" echo "2) Green" echo "3) Blue" read colour case {colour} in Black) echo "You have choosen the Black colour..!!" ;; Red) echo "You have choosen the Red colour..!!" ;; Blue) echo "You have choosen the Blue colour..!!" ;; *) echo "The colour you choose is unavailable.." ;; esac
Output:
Choose the color: 1)Black 2)Red 3)Blue Black You have choosen the Black colour..!!
Subscribe to my newsletter
Read articles from Mohammed Tamim Rawoot directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by