KandZ – Tuts

We like to help…!

Linux CLI 57 🐧 shell scripts functions

a - functions in shell scripts
Functions within shell scripts allow you to encapsulate code into reusable blocks
It makes your scripts cleaner and more maintainable
Defining a Function → A function in a shell script can be defined using the function keyword
or simply by putting parentheses after the function name
function greet() { } → Method 1: Using the 'function' keyword
greet2() { } → Method 2: Without the 'function' keyword
Calingl a function → You can call a function by just writing its name
greet → calling a function

b - Passing arguments to a function in shell scripts
You can pass arguments to a function just like you would with any other command.
arguments are values that are passed to function
The arguments are accessed using $1, $2, etc...
$1 is the first argument, $2 is the second, and so on.
$0 refers to the function name
greet3() { } → Define a function that takes two arguments
greet "Kronos" 30 → Call the function with arguments

c - Returning values from a function in shell scripts
In shell scripting, functions don't return values like in some other programming languages.
Instead, they can modify variables or print output that can be captured by the caller.
the most common way to return values is by using echo
echo $sum → prints the result
result=$(add 5 3) → Call the function and capture its output
alternative way is to modify global variables but it does not return a value

Leave a Reply