Unix Shell functions

Function is a series of instruction/commands. Function performs particular activity in shell i.e. it had specific work to do or simply say task.

When program gets complex we need to use divide and conquer technique. It means whenever programs gets complicated, we divide it into small chunks/entities which are known as functions.

Syntax:

C++

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

function-name()

{

command1

command2

.....

...

commandN

return

}

Where function-name is name of your function, that executes series of commands. A return statement will terminate the function.

Ex1:

C++

1

2

3

4

5

6

7

8

9

10

11

12

13

#!/bin/sh

SayHello()/* Define your function here */

{

echo"Hello Selva, Have a nice day"

return

}

SayHello/* Invoking Function here */

Output:

C++

1

Hello Selva,Haveanice day.

Note:

To execute this SayHello() function just type it name as mentioned in above example.

Ex2:

C++

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

#!/bin/sh

hello()

{

echo"HELLO Selva GOOD MORNING"

return

}

hai()

{

echo"HAI Selva"

return

}

hai

hello

exit

hai

Output:

C++

1

2

3

HAI Selva

HELLO Selva GOOD MORNING

Note:

In the above example, the function “hai” has been called again after the “exit” statement. So, script did not execute the “hai” again. Whatever the function/commands called after the exit statement will not be executed.