Functions, Case in Linux Shell Scripting

Unmesh SutarUnmesh Sutar
2 min read

Topics:

-Function

-Case

Functions

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

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

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

Syntax:

Function_Name () {
    #Statements
}

Example:

- A program to print Hello World

#!/bin/bash
Hello () {
    echo "Hello World"
}    

print_Hello

Case

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

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

Syntax:

case ${var} in
1)
    #Statement1
;;
2)
    #Statement2
;;
*)
    #Default Statement
;;
esac

Example:

#Write a case program to execute some commands in Linux

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

echo "Enter the value : "
read value

case ${value} in
1)
    echo "Enter the file name : "
    read filename
    touch /tmp/${filename}
;;
2)
    pwd
;;
3)
    echo "Enter the directory name : "
    read dirname
    mkdir /tmp/${dirname}
;;
4)
    ifconfig
;;
*)
    echo "Invalid Option"
;;
esac

Thanks for reading my blog till end!!

And also thanks to Mr. Pranav Jambare sir for conducting such an interactive and exquisite Workshop about the Basics of Linux to Shell Script.

10
Subscribe to my newsletter

Read articles from Unmesh Sutar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Unmesh Sutar
Unmesh Sutar