Functions in Shell Script - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

demo-image

Functions in Shell Script

Share This

Shell function provides a way of mapping a name to a list of commands. Shell function can be compared with subroutines or procedures or functions of programming languages.

The main difference is that a new instance of the shell begins in order to run a shell script, whereas functions run in the current shell.

The following examples illustrate valid and invalid function definitions:

1
2
3
4
lsl() { ls -l ; } # valid
lsl { ls -l ; } # invalid
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Invoking a Function

To invoke a function, only its name is required, thus typing


1
2
3
$ lsl
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

on the command line executes the lsl() function, but typing


1
2
3
$ lsl()
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

does not work because sh interprets this as a redefinition of the function by the name lsl.


Happy Exploring!

Comment Using!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.