Mosty Mostacho
Mosty Mostacho

Reputation: 43494

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.

Upvotes: 13

Views: 30086

Answers (2)

Alfred  Huang
Alfred Huang

Reputation: 463

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

Upvotes: 19

Daniel Brockman
Daniel Brockman

Reputation: 19290

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

amount=1
display_value $amount
amount=2
display_value $amount

Upvotes: 22

Related Questions