How to use Function in shell scripting

How to use Function in shell scripting


In this article, we will see that how to use about the shell functions. Functions enable you to break down the overall functionality of a script into smaller, logical subsections, which can then be called upon to perform their individual tasks when needed.


Using functions to perform repetitive tasks is an excellent way to create code reuse. This is an important part of modern object-oriented programming principles.

Shell functions are similar to subroutines, procedures, and functions in other programming languages.

Creating Functions

To declare a function, simply use the following syntax −

function_name () { 
   list of commands
}





The name of your function is function_name, and that's what you will use to call it from elsewhere in your scripts. The function name must be followed by parentheses, followed by a list of commands enclosed within braces.


#! /bin/bash

function name(){
    commands
}
name(){
    commands
}


Example:

function Hello(){
    echo "Hello"
}
quit(){
    exit
}

Hello
echo "fool"





#function with argument whatever you want to add argument in function but make sure that quit function always be in last

function print(){
    echo $0 $1 $2 $3 $4
}
quit(){
    exit
}

print Hello raju
print My name is kali
echo "fool"
quit

#local variable and print that file in function

function print(){
    name=$1
    echo "The name is $name"
}
print tam

#local command is used in the function to not change global command variable during output

function print(){
   local name=$1
    echo "The name is $name"
}

name="man"
echo "Name is $name before"
print tam
echo "Name is $name after"







Share:

0 comments

Please leave your comments...... Thanks