Lecture # 6 - Functions in Shell Script
Functions declaration. Function Calling. Returning Values from Functions. Function Parameters.
Functions in Shell Script:
In shell scripting, functions allow you to encapsulate a sequence of commands and execute them as a single unit. Functions help in modularizing code, improving readability, and promoting code reusability. Syntax to declare a function is:
function_name() {
# Function body (sequence of commands)
}
Function Parameters:
You can pass parameters to a function just like you pass arguments to a script. Inside the function, you can refer to these parameters using special variables
$1
,$2
, and so on, which represent the first, second, and subsequent parameters passed to the function.
Returning Values from Function:
In shell scripting, you can use the
return
statement to return a value from a function. The value returned by the function can be accessed using the special variable$?
after calling the function.