Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a function in shell script that receives parameters?

I'm working on a shell script and I have some lines of code that are duplicated (copy pasted, let's say).

I want those lines to be in a function. What is the proper syntax to use?

And what changes shoud I do in order for those functions to receive parameters?

Here goes an example.

I need to turn this:

amount=1
echo "The value is $amount"
amount=2
echo "The value is $amount"

Into something like this:

function display_value($amount) {
    echo "The value is $amount"
}

amount=1
display_value($amount)
amount=2
display_value($amount)

It is just an example, but I think it's clear enough.

Thanks in advance.

like image 338
Mosty Mostacho Avatar asked Oct 05 '11 00:10

Mosty Mostacho


People also ask

How do you call a function with parameters in shell script?

To invoke a function, simply use the function name as a command. To pass parameters to the function, add space-separated arguments like other commands. The passed parameters can be accessed inside the function using the standard positional variables i.e. $0, $1, $2, $3, etc.

Can shell script take parameter?

A bash shell script have parameters. These parameters start from $1 to $9. When we pass arguments into the command line interface, a positional parameter is assigned to these arguments through the shell. The first argument is assigned as $1, second argument is assigned as $2 and so on...

How can we create a function in shell script?

Creating Functions The name of your function is function_name, and that's what you will use to call it from elsewhere in your scripts. The function name must be followed by parentheses, followed by a list of commands enclosed within braces.

How do I pass an argument to a function in bash?

Bash Function Arguments To pass arguments to a function, add the parameters after the function call separated by spaces.


2 Answers

function display_value() {
    echo "The value is $1"
}

amount=1
display_value $amount
amount=2
display_value $amount
like image 78
Daniel Brockman Avatar answered Oct 24 '22 08:10

Daniel Brockman


In a shell script, functions can accept any amount of input parameters. $1 stands for the 1st input parameter, $2 the second and so on. $# returns the number of parameters received by the function and $@ return all parameters in order and separated by spaces.

For example:

  #!/bin/sh
  function a() {
   echo $1
   echo $2
   echo $3
   echo $#
   echo $@
  }

  a "m" "j" "k"

will return

m
j
k
3
m j k
like image 15
Alfred Huang Avatar answered Oct 24 '22 08:10

Alfred Huang