• Arun Kumar

Functions in Linux Shell

Linux shell functions allow you to package a set of commands into one code block which can be called any number of times. This makes your shell programs small in length and increases re-usability of code.


Simple Linux Function


There are two ways to define a Linux function. Method 1 is the most preferred one

Method 1

<function-name> () {
    commands
}

Method 2

function <function-name> {
    commands
}

Let's use Linux functions to print Hello World

#!/bin/bash

#define the function

hello_world () {
    echo "hello world"
}

#call the function

hello_world

You must always first define the function before calling it. By simply giving the function name, you are calling/executing the function.



Linux Function With Parameters


You can pass parameters to Linux functions based on positional reference

hello_world This is default text

$1 = This
$2 = is
$3 = default
$4 = text
....

You refer to parameters passed to a function based on position 1,2,3 and so on. Let's look at another Linux function which accepts parameters to process results

#!/bin/bash

#define the function

hello_world () {
    echo "Your first name is: $1"
    echo "Your last name is: $2"
}

#call the function

hello_world Arun Kumar

Simple Calculator With Linux Functions


Let's use a Linux function to get sum of two numbers

#!/bin/bash

#create function to add
add_num () {
    sum=$(( $1+$2 ))
    echo "Total: $sum"
}

#ask two numbers from the user
read -p "Enter number 1: " num1
read -p "Enter number 2: " num2

add_num num1 num2

❤️❤️❤️

80 views

Recent Posts

See All