Skip to main content

Command Palette

Search for a command to run...

Linux Shell Scripting : Functions &Cases

Day-9 : Linux Workshop

Updated
2 min readView as Markdown
Linux Shell Scripting : Functions &Cases
V

Student, COEP'27 | DBATU'24 | Member of CSI COEP | Full Stack Developer | DSA Enthusiast | Explorer |

These were the topics that are covered during this session.

Functions

  • Functions refer to blocks of code that can be defined and executed within scripts or the command line.

  • These functions allow you to modularize your code, making it easier to manage, reuse, and understand.

  • Functions can accept parameters and return values, just like in programming languages.

#Syntax:
Function_Name () {
    #Statements
}
#Example:
#A function to print "Hello Linux" on terminal

#!/bin/bash
#Function Defination
print_Hello () {
    echo "Hello Linux"
}    

#Function Call
print_Hello

Function To Add Two Numbers

#!/bin/bash
#Function Defn
addTwoNumbers () {
    echo "Enter the first number:"
    read num1

    echo "Enter the second number:"
    read num2

    sum=$(expr $num1 + $num2)
    echo "The addition of ${num1} + ${num2} is : ${sum}"
} 

#Function Call
addTwoNumbers

#Output:
Enter the first number:
10
Enter the second number:
20
The addition of 10 + 20 is : 30

Case

  • In Linux Shell Scripting, "cases" refer to switch/case statements.

  • These are control structures that allow you to perform different actions based on the value of a variable or expression.

#Syntax:
case ${variable} in
val1)
    #Statement1
;;
val2)
    #Statement2
;;
*)
    #Default Statement
;;
esac
#Example:
#Write a case which when executes, perform some commands in Linux

#!/bin/bash
echo "1 : File Create"
echo "2 : Display IP Address"
echo "3 : Current Directory"
echo "4 : Make Directory"

echo "Enter the input : "
read input

case ${input} in
1)
    echo "Enter the file name : "
    read fileName
    touch /tmp/${filename}
;;
2)
    ifconfig
;;
3)
    pwd
;;
4)
    echo "Enter the directory name : "
    read dirName
    mkdir /tmp/${dirname}
;;
*)
    echo "I can't do it !!"
;;
esac

#Executing the Script...
1 : File Create
2 : Display IP Address
3 : Current Directory
4 : Make Directory
Enter the input :
3
/home/viraj

This was our last lecture at the Linux Workshop. Pranav Jambare (DevOps @TCS), delivered an exceptional amount of lectures. His guidance led us through intricate Linux landscapes, mastering commands and scripting. His passion and support created a vibrant learning environment, igniting our love for Linux.

A big thank you to Pranav Sir for an amazing workshop.