pass parameters to shell script functions

How to Pass Parameters to Shell Script Function

Sometimes you may need to pass parameters & arguments to shell script functions. Shell script functions do not support arguments the way other programming languages do. Nevertheless, there are ways to do this and we will be looking at them in this article. Here are a couple of ways to pass parameters to shell script functions.


How to Pass Parameters to Shell Script Function

Typically, in other scripting languages, you can pass arguments and parameters to functions as function_name(parameter1, parameter2, …) This is not supported in shell script functions. In shell script functions, you can directly pass parameters during function call, without defining their names in your function definition, and directly refer to them using positional parameters $1 for first argument, $2 for second argument and so on.

Let us look at it with an example. There are two ways to define functions in shell script.

function function_name {
    ... 
} 

OR

function_name () {
    ... 
}

Whether you pass any argument or not, each shell script function must be defined as shown above. You will notice that we have not specified any argument in function signature.

Here is how you call the same shell script function

function_name arg1 arg2 ...

As mentioned earlier, each shell script function refers to arguments by their position $1, $2, and so on. $0 refers to the name of the function.

Here is an example of a shell script function that reads the first argument and echoes it. Create an empty shell script as shown below.

$ sudo vi test_script.sh

Add the following lines to it.

#!/usr/bin/env sh

test() {
    echo "Parameter #1 is $1"
}

test 20

Run the above script with the following command.

$ sudo ./test_script.sh
Parameter #1 is 20

It is important to remember that you should call your function only after its definition. If you call it before the definition, then it will give you an error.

You may also call variables defined outside your shell script function and use them as parameters. In the following example, we have used a variable $name defined outside our function as a parameter

$ sudo vi test_script.sh

Add the following lines to it.

test() {
    echo hello $name
}

name="tom"
test

Run the above script with the following command.

$ sudo ./test_script.sh
hello tom

In this article, we have looked at two different ways to pass parameters to shell script functions.

Also read :

How to Force NGINX to Serve New Static Files
How to Return Value in Shell Script
How to Retrieve POST data request in Django
How to Temporarily Disable Foreign Key Check in MySQL
How to Run Python Script in Django

Leave a Reply

Your email address will not be published. Required fields are marked *