Skip to main content

Functions in Bash shell



Functions in Bash Scripting are a great way to reuse code. In this section you'll learn how they work and what you can do with them.
Think of a function as a small script within a script. It's a small chunk of code which you may call multiple times within your script. They are particularly useful if you have certain tasks which need to be performed several times. Instead of writing out the same code over and over you may write it once in a function then call that function every time.
Creating a function is fairly easy. They may be written in two different formats: 

function_name ()
{

}

or
function function_name
{

}

The function can be called with just function_name
Example1:
f()
{
echo “This is a test function...f”
}
f
Example2:
function f
{
echo “This is a test function...f”
}
f

Passing Arguments

It is often the case that we would like the function to process some data for us. We may send data to the function in a similar way to passing command line arguments to a script. We supply the arguments directly after the function name. Within the function they are accessible as $1, $2, etc.
Example:
f()
{
echo "first argument is=$1"
echo "second argument is= $2"
}
f first second # function call with arguments

Return Values
Most other programming languages have the concept of a return value for functions, a means for the function to send data back to the original calling location. Bash functions don't allow us to do this. They do however allow us to set a return status. Similar to how a program or command exits with an exit status which indicates whether it succeeded or not. We use the keyword return to indicate a return status.
Typically a return status of 0 indicates that everything went successfully. A non zero value indicates an error occurred.
We can use command substitution to return some value.
Example:
lines_in_file () {
cat $1 | wc -l
}
num_lines=$( lines_in_file file )
echo The file has $num_lines lines in it.

Variable scope
Scope refers to which parts of a script can see which variables. By default a variable is global. This means that it is visible everywhere in the script. We may also create a variable as a local variable. When we create a local variable within a function, it is only visible within that function. To do that we use the keyword local in front of the variable the first time we set it's value.
local var_name=value
It is generally considered good practice to use local variables within functions so as to keep everything within the function contained. This way variables are safer from being inadvertently modified by another part of the script which happens to have a variable with the same name (or vice versa). 

Example:
var_change ()
{
local var1='local 1'
echo Inside function: var1 is $var1 : var2 is $var2
var1='changed again'
var2='2 changed again'
}
var1='global 1'
var2='global 2'
echo Before function call: var1 is $var1 : var2 is $var2
var_change 
echo After function call: var1 is $var1 : var2 is $var2

Comments

Popular posts from this blog

Introduction to Data Structures

Visit My Data Structure Blog for Programs... It is important for every Computer Science student to understand the concept of Information and how it is organized or how it can be utilized. If we arrange some data in an appropriate sequence, then it forms a Structure and gives us a meaning. This meaning is called Information . A data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently. Data may be organized in many different ways. The logical model of a particular organization of data in a computer is called data structure. The choice of the model based on two considerations. It should be reflect the data in the real world. It should be simple that one can effectively process the data when necessary. E.g. Array, linked list, stack, queue, tree, graph Data structure can be classified into two: Linear: A data structure is said to be linear if its elements form a sequence E.g. Array, linked list, stack, queue Non-Linear: A dat

Basic Linux Commands For Beginner's

Basic Linux Commands for Beginners Linux is an Operating System’s Kernel. You might have heard of UNIX. Well, Linux is a UNIX clone. But it was actually created by Linus Torvalds from Scratch. Linux is free and open-source, that means that you can simply change anything in Linux and redistribute it in your own name! There are several Linux Distributions, commonly called “distros”. A few of them are: Mint Ubuntu Linux Red Hat Enterprise Linux Debian Fedora Kali Linux is Mainly used in Servers. About 90% of the Internet is powered by Linux Servers. This is because Linux is fast, secure, and free! The main problem of using Windows Servers are their cost. This is solved by using Linux Servers. Forgot to mention, the OS that runs in about 80% of the Smartphones in the World, Android, is also made from the Linux Kernel. Yes, Linux is amazing! A simple example of its security is that most of the viruses in the world run on Windows, but not on Linux

KTU-FOSS LAB Solutions

Write shell scripts to show the following  ( you can write menu driven programs)  Currently logged user and his logname   ( logname, id -un, echo $USER)  Your current shell ( echo $SHELL)  Your home directory ( echo $HOME)  Your operating system type (echo $OSTYPE)  Your current path setting ( echo $PATH)  Your current working directory ( echo $PWD )  Show Currently logged  users ( w or who -H)      Show only the user name of logged users in the host ( users)      Details of last login ( last mec  ;where mec is the user id )  About your OS and version, release number, kernel version                                                 ( uname -a or  cat  /proc/version)  Show all available shells ( cat /etc/shells )  Show mouse settings (cat  /sys/class/input/mouse*/device/name )  Show computer CPU information       CPU details      ( cat /proc/cpuinfo | more )       Show information on  CPU architecture ( lscpu)       Number of Processo