Home Linux Functions in Shell Scripting

Functions in Shell Scripting

by Anup Maurya
19 minutes read

In Shell Scripting, a function is a set of commands that are written to perform a specific task. Functions allow us to organize our code into smaller, more manageable pieces that can be reused throughout the script. They also help to make our scripts more readable and maintainable.

Defining a Function

In shell scripting, you can define a function using the ‘function’ keyword or by simply defining a name for your function followed by parentheses “()”. Here’s an example:

function my_function() {
    # commands go here
    echo "Hello World!"
}

Or

my_function() {
    # commands go here
    echo "Hello World!"
}

In the above example, we have defined a function called ‘my_function’ that will simply print “Hello World!” to the console.

Calling a Function: To call a function, simply use its name followed by parentheses “()”. Here’s an example:

my_function

This will execute the ‘my_function’ function and output “Hello World!” to the console.

Passing Arguments to a Function: You can also pass arguments to a function in shell scripting. Arguments are passed to the function in the same way as command-line arguments. Here’s an example:

my_function_with_args() {
    echo "Hello $1"
}

my_function_with_args "John"

In the above example, we have defined a function called ‘my_function_with_args’ that takes one argument and outputs “Hello <argument>” to the console. When we call the function with “John” as the argument, it will output “Hello John”.

Returning a Value from a Function: Functions in shell scripting can also return a value. To return a value from a function, you can use the ‘return’ keyword followed by the value you want to return. Here’s an example:

my_function_with_return() {
    local result="Hello $1"
    echo $result
    return 0
}

output=$(my_function_with_return "Jane")
echo $output

In the above example, we have defined a function called ‘my_function_with_return’ that takes one argument and returns a string that says “Hello <argument>”. When we call the function with “Jane” as the argument, it will return the string “Hello Jane”. We then assign the output of the function to a variable called ‘output’ and print it to the console.

Conclusion

Functions are a powerful tool in shell scripting that allow you to organize your code into smaller, more manageable pieces that can be reused throughout your script. They can take arguments, return values, and help to make your scripts more readable and maintainable. By mastering the use of functions, you can write more efficient and effective shell scripts.

related posts

Leave a Comment